I m试图在校读简单的校对池方案。 但是,看来<代码>pthread_cond_signal。 这造成了问题。 例如,我要说的是“生产者-消费者”方案:
pthread_cond_t my_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t my_cond_m = PTHREAD_MUTEX_INITIALIZER;
void * liberator(void * arg)
{
// XXX make sure he is ready to be freed
sleep(1);
pthread_mutex_lock(&my_cond_m);
pthread_cond_signal(&my_cond);
pthread_mutex_unlock(&my_cond_m);
return NULL;
}
int main()
{
pthread_t t1;
pthread_create(&t1, NULL, liberator, NULL);
// XXX Don t take too long to get ready. Otherwise I ll miss
// the wake up call forever
//sleep(3);
pthread_mutex_lock(&my_cond_m);
pthread_cond_wait(&my_cond, &my_cond_m);
pthread_mutex_unlock(&my_cond_m);
pthread_join(t1, NULL);
return 0;
}
如我删除<编码>sleep。 电话:main(
)可能受阻,因为它没有从<代码>liberator()上接过电话。 当然,sleep
这对于确保两者都不会有那么强。
在现实生活中,这将是一位工人对管理人员说,他们已经做好了工作准备,或者管理人员已经宣布新的工作是可用的。
你们如何在read子里可靠地这样做?
Elaboration
@Borealid 回答类型的工作,但他对这个问题的解释可能更好。 我建议,研究这一问题的任何人在评论中阅读讨论,以了解正在发生什么。
我尤其要修改他的回答和照例,使这一点更加明确。 (Since Borealid的原始答复,虽然编辑和工作,但混淆了我的许多工作)
// In main
pthread_mutex_lock(&my_cond_m);
// If the flag is not set, it means liberator has not
// been run yet. I ll wait for him through pthread s signaling
// mechanism
// If it _is_ set, it means liberator has been run. I ll simply
// skip waiting since I ve already synchronized. I don t need to
// use pthread s signaling mechanism
if(!flag) pthread_cond_wait(&my_cond, &my_cond_m);
pthread_mutex_unlock(&my_cond_m);
// In liberator thread
pthread_mutex_lock(&my_cond_m);
// Signal anyone who s sleeping. If no one is sleeping yet,
// they should check this flag which indicates I have already
// sent the signal. This is needed because pthread s signals
// is not like a message queue -- a sent signal is lost if
// nobody s waiting for a condition when it s sent.
// You can think of this flag as a "persistent" signal
flag = 1;
pthread_cond_signal(&my_cond);
pthread_mutex_unlock(&my_cond_m);