当前位置: 技术问答>linux和unix
linux条件锁
来源: 互联网 发布时间:2017-05-07
本文导语: 父线程里: pthread_mutex_lock(&s_startupMutex); pthread_attr_t attr; pthread_attr_init (&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); printf("server_create_child_threadn"); err = pthread_create(child_thread_value,&attr,chi...
父线程里:
pthread_mutex_lock(&s_startupMutex);
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
printf("server_create_child_threadn");
err = pthread_create(child_thread_value,&attr,child_thread,(void *)&peer );
while (child_thread_start == 0) {
printf("child_thread_start=0n");
pthread_cond_wait(&s_startupCond, &s_startupMutex);
}
child_thread_start=0;
pthread_mutex_unlock(&s_startupMutex);
子线程里:
pthread_mutex_lock(&s_startupMutex);
sock_number = *(int *)sock_file_num;
child_thread_start = 1;
printf("broadcastn");
pthread_cond_broadcast(&s_startupCond);
pthread_mutex_unlock(&s_startupMutex);
这里子线程明明广播了条件信号,为什么父线程还是一直阻塞等待呢,像是完全没有被唤醒
pthread_mutex_lock(&s_startupMutex);
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
printf("server_create_child_threadn");
err = pthread_create(child_thread_value,&attr,child_thread,(void *)&peer );
while (child_thread_start == 0) {
printf("child_thread_start=0n");
pthread_cond_wait(&s_startupCond, &s_startupMutex);
}
child_thread_start=0;
pthread_mutex_unlock(&s_startupMutex);
子线程里:
pthread_mutex_lock(&s_startupMutex);
sock_number = *(int *)sock_file_num;
child_thread_start = 1;
printf("broadcastn");
pthread_cond_broadcast(&s_startupCond);
pthread_mutex_unlock(&s_startupMutex);
这里子线程明明广播了条件信号,为什么父线程还是一直阻塞等待呢,像是完全没有被唤醒
|
试了一下,能够唤醒阿,以下是根据楼主代码写的程序
以下是编译命令
以下是结果
#include
#include
#include
#include
#include
pthread_cond_t s_startupCond;
pthread_mutex_t s_startupMutex;
int child_thread_start=0;
void *child_thread()
{
pthread_mutex_lock(&s_startupMutex);
child_thread_start = 1;
printf("broadcastn");
pthread_cond_broadcast(&s_startupCond);
pthread_mutex_unlock(&s_startupMutex);
}
int main()
{
pthread_t child_thread_value;
pthread_mutex_lock(&s_startupMutex);
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
printf("server_create_child_threadn");
int err = pthread_create(&child_thread_value,&attr,child_thread,(void *)NULL);
while (child_thread_start == 0) {
printf("child_thread_start=0n");
pthread_cond_wait(&s_startupCond, &s_startupMutex);
}
printf("pthread_cond_wait return and child_thread_start == 1n");
child_thread_start=0;
pthread_mutex_unlock(&s_startupMutex);
return 0;
}
以下是编译命令
gcc -o test test.c -lpthread
以下是结果
server_create_child_thread
child_thread_start=0
broadcast
pthread_cond_wait return and child_thread_start == 1