我的一位同事让我为他写一份作业.虽然这不太符合道德规范,但我还是认罪.这就是问题所在:用C编写程序,计算序列1 2 + 2 2 + ... + n 2.假设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);
}
Run Code Online (Sandbox Code Playgroud)
除了逻辑/句法的观点,我想知道:
提前谢谢,我期待着阅读你的想法
您在计算之前正在获取互斥锁.您应该在汇总到本地值之前立即执行此操作.
pthread_mutex_lock(&mtx);
total_sum += local_sum;
pthread_mutex_unlock(&mtx);
Run Code Online (Sandbox Code Playgroud)
这取决于您拥有多少CPU.使用单个CPU内核,计算绑定程序永远不会在多个线程上运行得更快.
此外,由于你所做的所有工作都是锁定的,你最终只能运行一个单独的线程,所以无论如何它都是有效的单线程.