【问题标题】:Incorrect output of code after using pthreads使用 pthread 后代码输出不正确
【发布时间】:2015-04-22 10:49:07
【问题描述】:

我正在编写一些代码,试图让它使用线程,但收效甚微。代码如下(使用一些网上的tuts)

(1) 创建一个数组来保存要传递给每个线程的参数。 (2) 存储线程参数的结构体 (3) 每个线程执行的函数 (4) Main,我在这里创建每个 pthread 并传递 args。 endbegin 是虚拟的 ii+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


【解决方案1】:

您的main 在其他线程之前终止。 main 比较特殊,从它返回相当于调用exit

要么使用pthread_exit 结束main,要么使用pthread_join 等待其他线程的终止。

【讨论】:

  • 因为像我这样的初学者可能会看到这个,这是我添加的代码for (i=0; i&lt;n_th; i++) {pthread_join(threads[i], NULL);}
【解决方案2】:

pthread_join 将解决这个问题,在 main 中为每个创建的线程调用它。调用pthread_join() 函数以等待线程完成。如果 main 在线程完成之前完成,它们将在完成工作之前死亡。

【讨论】:

  • 因为像我这样的初学者可能会看到这个,这是我添加的代码for (i=0; i&lt;n_th; i++) {pthread_join(threads[i], NULL);}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多