【问题标题】:Using threads in C. Getting unexpected results在 C 中使用线程。得到意想不到的结果
【发布时间】:2015-08-15 07:08:41
【问题描述】:

我刚接触 C 中的线程。 所以从最基本的开始。 我只是想创建线程并对其使用互斥。 我已经声明了三个函数并为它们创建了 3 个线程,但是每次我执行我的程序时,并不是所有三个进程都会一直执行

请给出解决方案。

【问题讨论】:

  • 您没有正确调用pthread_join,请查看手册页。
  • 我已经回滚了您最近的编辑,这基本上破坏了问题。
  • 编辑了问题并删除了代码,因为这是我班级的作业,我不希望它被复制

标签: c multithreading mutex


【解决方案1】:

您必须在pthread_join() 中传递线程对象,请参见更新的第35、38、41 行。

函数的定义是int pthread_join(pthread_t thread, void **retval);

这会有所帮助。

 34     thread1=pthread_create(&trd1,NULL,process1,(void *)nargs1);
 35     pthread_join(trd1, NULL);
 36
 37     thread2=pthread_create(&trd2,NULL,process2,(void *)nargs2);
 38     pthread_join(trd2, NULL);
 39
 40     thread3=pthread_create(&trd3,NULL,process3,(void *)nargs3);
 41     pthread_join(trd3, NULL);

【讨论】:

  • 仍然没有得到想要的输出。虽然如果我在主函数返回之前将睡眠放在它工作。任何人都可以提出为什么上面的代码不能像 join 一样等待。
  • 感谢它的回答。正在加入错误参数的线程。
猜你喜欢
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多