目前我正在开发一个使用线程来计算平方根和的程序。我的程序可以运行,但是其中一个要求是使用主线程来查找初始值,一旦我从 main 调用函数 Void *calc ,程序就会中断。有没有某种方法可以进行这样的函数调用?这是因为函数是指针吗?感谢您的帮助。
#include <pthread.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#define NUM_THREADS 3
int ARGV;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
double total = 0;
void *calc(void* t){
int ph = (int)t + 1;
int start, stop, interval_size;
interval_size = ARGV/(NUM_THREADS + 1);
start = ((ph) * interval_size) + 1;
stop = (ph * interval_size) + 1;
double ttl;
int i;
for (i = start; i <= stop; i++){
ttl = ttl + sqrt(i);
printf("Total Thread %i %lf\n", ph, ttl);
}
pthread_mutex_lock(&m);
total = total + ttl;
pthread_mutex_unlock(&m);
pthread_exit(NULL);
}
int main(int argc, char* argv[]) {
int i;
double ttl;
ARGV = atoi(argv[1]);
pthread_t ti[NUM_THREADS];
calc(0);
for (i = 0; i < NUM_THREADS; i++) {
pthread_create(&ti[i], NULL, calc,(void *)i);
}
/*for (i = 1; i <= (ARGV / 4) ; i++){
ttl = ttl + sqrt(i);
}*/
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(ti[i], NULL);
}
total = total + ttl;
printf("Result: %lf\n", total);
}
程序中断,因为函数似乎只被调用一次,而不是每个线程都使用该函数。打印出来的唯一值是一些模糊的错误数字。
最佳答案
您的 calc
函数执行 pthread_exit
。现在 pthread_exit
可以而且应该从主线程调用,所以没问题
To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).
但由于这发生在任何其他线程创建之前,程序直接退出,而不会启动其他线程。
关于在 C 中从 main 调用 void* 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19145719/