除此之外,
pthread_create(&thr[i], 0, makeRequest, &i);
不正确,因为i 是一个局部变量,所以&i 是您对pthread_create 的所有调用的同一个指针
您通常应该将数据指针指向您的线程例程 - 这里的线程例程是makeRequest 静态指针或唯一指针(每个线程唯一);在实践中,让它成为一些malloc-ed 内存的指针。
更好的做法是声明一些struct my_thread_data_st,用
在堆中唯一地分配它
struct my_thread_data_st* td = malloc(sizeof(struct my_thread_data_st));
if (!td) perror("malloc td"), exit(EXIT_FAILURE);
memset (td, 0, sizeof(struct my_thread_data_st));
// fill td appropriately, then
pthread_create(&thr[i], 0, makeRequest, td);
或者你可以有一个数组,例如int-s,例如int num[4];,适当初始化,然后pthread_create(&thr[i], 0, makeRequest, &num[i]);
当然,如果td 是通过malloc 进行堆分配的,请不要忘记在适当的时间使用free,例如线程结束后(例如,在 pthread_join-ed 之后)。您可能还对Boehm's GC 感兴趣,并使用GC_malloc 而不是malloc(那么,不用担心释放内存,GC 会这样做)。
如果线程正在访问共享数据,您应该使用一些 [全局或静态] 互斥锁(使用 pthread_mutex_lock 和 pthread_mutex_unlock)序列化对它的访问
在退出之前不要忘记在所有线程上调用pthread_join -e.g.从main返回。
我建议阅读一些pthreads tutorial 和一些关于advanced linux programming 的书。