【发布时间】:2009-05-17 20:37:03
【问题描述】:
我的一位同事让我为他写作业。虽然这样做不太合乎道德,但我还是认罪了。 问题是这样的: 用 C 编写一个程序,计算序列 12 + 22 + ... + n2。 假设 n 是 p 的倍数,p 是线程数。 这是我写的:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define SQR(X) ((X) * (X))
int n, p = 10, total_sum = 0;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
/* Function prototype */
void *do_calc(void *arg);
int main(int argc, char** argv)
{
int i;
pthread_t *thread_array;
printf("Type number n: ");
fscanf(stdin, "%d", &n);
if (n % p != 0 ) {
fprintf(stderr, "Number must be multiple of 10 (number of threads)\n");
exit(-1);
}
thread_array = (pthread_t *) malloc(p * sizeof(pthread_t));
for (i = 0; i < p; i++)
pthread_create(&thread_array[i], NULL, do_calc, (void *) i);
for (i = 0; i < p; i++)
pthread_join(thread_array[i], NULL);
printf("Total sum: %d\n", total_sum);
pthread_exit(NULL);
}
void *do_calc(void *arg)
{
int i, local_sum = 0;
int thr = (int) arg;
pthread_mutex_lock(&mtx);
for (i = thr * (n / p); i < ((thr + 1) * (n / p)); i++)
local_sum += SQR(i + 1);
total_sum += local_sum;
pthread_mutex_unlock(&mtx);
pthread_exit(NULL);
}
除了逻辑/句法的观点,我想知道:
- 各个非多线程程序将如何执行
- 我如何测试/查看它们的性能
- 不使用线程的程序会是什么
提前致谢,我期待阅读您的想法
【问题讨论】:
标签: c multithreading unix