我试图弄清楚如何摆脱对pthread_timedjoin_np的依赖,因为我试图在OSX上构建一些代码.
现在我有一个我正在弹出的线程队列,执行pthread_timedjoin_np,如果他们没有返回,他们会被推回队列.
为每个线程调用的thread_function的结尾执行pthread_exit(0); 以便接收线程可以检查返回值为零.
我想我可能会尝试使用pthread_cond_timedwait()来实现类似的效果,但我想我错过了一步.
我以为我能够使工作线程A信号成为互斥锁中的条件和pthread_exit(),并且工作线程B可以唤醒信号,然后是pthread_join().问题是,线程B不知道哪个线程抛出了条件信号.我是否需要明确地将其作为条件信号的一部分传递或者什么?
谢谢
德里克
在操作系统的进程同步中,条件变量的原理是什么?
我正在努力学习Unix C并做一些练习练习.我正在处理的当前问题涉及POSIX线程(主要是pthread_create()和pthread_join())
该问题要求使用两个线程重复打印"Hello World".一个线程是打印"Hello"1000次,而第二个线程打印"World"1000次.主程序/线程是在继续之前等待两个线程完成.
这就是我现在所拥有的.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
void *print_hello(void *arg)
{
int iCount;
for(iCount = 0; iCount < 1000; iCount++)
{
printf("Hello\n");
}
}
void *print_world(void *arg)
{
int iCount;
for(iCount = 0; iCount < 1000; iCount++)
{
printf("World\n");
}
}
int main(void)
{
/* int status; */
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, print_hello, (void*)0);
pthread_create(&thread2, NULL, print_world, (void*)0);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这似乎没有完全发挥作用.它按预期打印"Hello".但"世界"根本没有印刷.好像第二个线程根本没有运行.不确定我是否正确使用pthread_join.我的目的是让主线程"等待"这两个线程,因为练习要求.
任何帮助,将不胜感激.