日期:2014-05-16  浏览次数:20637 次

linux条件锁
父线程里:
  pthread_mutex_lock(&s_startupMutex);
  pthread_attr_t attr;
  pthread_attr_init (&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 
  printf("server_create_child_thread\n"); 
  err = pthread_create(child_thread_value,&attr,child_thread,(void *)&peer );

  while (child_thread_start == 0) {
    printf("child_thread_start=0\n");
    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("broadcast\n");
  pthread_cond_broadcast(&s_startupCond);
  pthread_mutex_unlock(&s_startupMutex);
这里子线程明明广播了条件信号,为什么父线程还是一直阻塞等待呢,像是完全没有被唤醒
------解决方案--------------------
试了一下,能够唤醒阿,以下是根据楼主代码写的程序

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

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("broadcast\n");
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_thread\n"); 
int err = pthread_create(&child_thread_value,&attr,child_thread,(void *)NULL);

while (child_thread_start == 0) {
printf("child_thread_start=0\n");
pthread_cond_wait(&s_startupCond, &s_startupMutex);
}
        printf("pthread_cond_wait return and child_thread_start == 1\n");
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