【发布时间】:2021-12-19 22:35:10
【问题描述】:
这就是我想要完成的。用 C(或 C++/C#)编写一个创建 5 个线程的多线程程序。每个线程应生成 1,000 个随机点并计算圆圈内出现的点数。主线程应该等待五个线程一个接一个地终止。一旦线程终止,主线程使用圆中的总点数和终止线程生成的总点数来更新 PI 的值。例如,主线程等待第一个线程终止。当第一个线程终止时,主线程合并第一个线程获得的圆中点的总数来更新PI的值。接下来,主线程等待第二个线程终止。当第二个线程终止时,主线程使用第二个线程获得的圆中点的总数来更新PI的值,以此类推。
我不断收到一条错误消息,说非 void 函数不返回值,那么无论如何我可以解决这个问题,或者有什么可供我选择的方法吗?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
long incircle = 0;
long ppt; /* points per thread*/
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *runner() {
long incircle_thread = 0;
unsigned int rand_state = rand();
long i;
for (i = 0; i < ppt; i++) {
double x = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
double y = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
if (x * x + y * y < 1) {
incircle_thread++;
}
}
pthread_mutex_lock(&mutex);
incircle += incircle_thread;
pthread_mutex_unlock(&mutex);
}
int main(int argc, const char *argv[])
{
if (argc != 3) {
fprintf(stderr, "usage: ./pi <total points> <threads>\n");
exit(1);
}
long totalpoints = atol(argv[1]);
int thread_count = atoi(argv[2]);
ppt = totalpoints / thread_count;
time_t start = time(NULL);
srand((unsigned)time(NULL));
pthread_t *threads = malloc(thread_count * sizeof(pthread_t));
pthread_attr_t attr;
pthread_attr_init(&attr);
int i;
for (i = 0; i < thread_count; i++) {
pthread_create(&threads[i], &attr, runner, (void *) NULL);
}
for (i = 0; i < thread_count; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
free(threads);
double points_per_thread = 0.0;
printf("Pi: %f\n", (4. * (double)incircle) / ((double)points_per_thread * thread_count));
printf("Time: %d sec\n", (unsigned int)(time(NULL) - start));
return 0;
}
'''
【问题讨论】:
-
请学会正确缩进你的代码。您在此处发布的混乱难以解析。正确缩进代码可以更容易阅读和理解,并遵循执行流程。错误信息也很清楚;你有一个函数说它返回一个值,而你的函数体中没有
return语句的值。当您缩进代码以使其可读时,您可能会自己发现问题。 -
在
runner的底部添加return (void *) 0;。
标签: c multithreading