我编写了一个程序,其中主线程创建一个线程并在辅助线程必须处理时发送一个事件,这在windows上工作得很好,但是当将它移植到* nix时很难实现相同的。< / p>
让我解释一下,请考虑以下
/* thread2 function */
thread_function_call()
{
/* be a consumer */
pthread_exit();
}
/* main function */
main()
{
/* create a thread */
pthread_create();
while(1)
{
/* produce the stuff for consumer or thread2 */
/* generate the event */
}
pthread_join();
}
这里是连续循环中的主线程,然后触发事件/调用thread2,一旦触发事件/调用thread2,就应该执行thread2函数。
这就像生产者和消费者问题,请考虑所有同步条件都已到位。
请帮助我最好地实现这个目标
答案 0 :(得分:2)
使用pthread实现生产者 - 消费者的一般方法是使用条件变量。消费者线程在pthread_cond_wait()
中阻止,生产者用pthread_cond_signal()
或pthread_cond_broadcast()
发信号通知它。