【发布时间】:2015-04-22 10:49:07
【问题描述】:
我正在编写一些代码,试图让它使用线程,但收效甚微。代码如下(使用一些网上的tuts)
(1) 创建一个数组来保存要传递给每个线程的参数。
(2) 存储线程参数的结构体
(3) 每个线程执行的函数
(4) Main,我在这里创建每个 pthread 并传递 args。 end 和 begin 是虚拟的 i 和 i+1 仅用于测试目的。
#include <pthread.h>
struct thread_data* thread_data_array;
struct thread_data{
int thread_id;
int begin;
int end;
};
void *proccessData(void *threadarg)
{
struct thread_data *my_data = (struct thread_data *) threadarg;
int id = my_data->thread_id;
int start = my_data->begin;
int end = my_data->end;
printf("%s%d%s%d%s%d%s","Process: Id ",id," begin: ",start," end: ",end,"\n");
// Init
FILE* fileOut;
// do stuff
fileOut = fopen(someNameUsingId, "w");
// more stuff
fclose(fileOut);
}
int main(int argc, char **argv)
{
int n_th = atoi(argv[1]);
thread_data_array = malloc(n_th*sizeof(struct thread_data));
pthread_t threads[n_th];
int i;
for (i=0; i<n_th; i++)
{
thread_data_array[i].thread_id = i;
thread_data_array[i].begin = i;
thread_data_array[i].end = i+1;
pthread_create(&threads[i], NULL, proccessData,(void *) &thread_data_array[i]);
}
}
我得到了什么:有时什么都没有打印,有时一些 id 被打印了两次。未创建文件(假设每 5 个文件中就有一个文件已创建,但为空)
但是正如我所期望的那样在主要作品中使用它,从 0 到 1 的 id 1 被打印,从 1 到 2 的 id 2 被创建,并且两个文件都被创建并且具有正确的内容
thread_data_array[0].thread_id = 1;
thread_data_array[0].begin = 0;
thread_data_array[0].end = 1;
proccessData((void *) &thread_data_array[0]);
thread_data_array[1].thread_id = 2;
thread_data_array[1].begin = 1;
thread_data_array[1].end = 2;
proccessData((void *) &thread_data_array[1]);
有人能指出我做错了什么,以及如何解决吗?
提前致谢
【问题讨论】:
-
我认为
main在线程之前结束,但无法弄清楚如何解决它 -
pthread_join将解决这个问题,在 main 中为每个创建的线程调用它 -
这有必要吗?因为我真的不需要加入他们,只是每个人都做自己的工作
-
pthread_join()函数被调用以等待线程完成。如果 main 在线程完成之前完成,它们将在完成工作之前死亡 -
它有效!谢谢。将其发布为答案,我会接受。你能解释一下为什么这是必要的吗?
标签: c multithreading pthreads