typedef union{struct __pthread_mutex_s __data ;char __size [ __SIZEOF_PTHREAD_MUTEX_T ];long int __align ;} pthread_mutex_t ;
#include
int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t *restrict attr);
/* Conditional variable handling. */#define PTHREAD_COND_INITIALIZER { { { 0 }, { 0 }, { 0 , 0 }, { 0 , 0 }, 0 , 0 , { 0 , 0 } } }
#include
int pthread_cond_destroy(pthread_cond_t *cond);
#include
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
#include
函数原型:
int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct timespec *restrict abstime);
#include
int pthread_cond_broadcast(pthread_cond_t *cond);
#include
int pthread_cond_signal(pthread_cond_t *cond);
- #include
- #include
- static pthread_t thread1;
- static pthread_t thread2;
-
- //静态初始化
- static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
- static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
- void *function1()
- {
- while(1)
- {
- pthread_mutex_lock(&lock);
- printf("===== 线程 1 进入睡眠 ====\n");
- pthread_cond_wait(&cond,&lock);
- printf("==== 线程 1 唤醒 ====\n");
- pthread_mutex_unlock(&lock);
- }
- }
-
- void *function2()
- {
- while(1)
- {
- pthread_mutex_lock(&lock);
- printf("===== 线程 2 进入睡眠 ====\n");
- pthread_cond_wait(&cond,&lock);
- printf("==== 线程 2 唤醒 ====\n");
- pthread_mutex_unlock(&lock);
- }
- }
-
- int main()
- {
- int i=0;
- if(-1==pthread_create(&thread1,NULL,function1,NULL))
- {
- printf("thread_create1 fail!\n");
- pthread_detach(thread1);
- }
- if(-1==pthread_create(&thread2,NULL,function2,NULL))
- {
- printf("thread_create fail!\n");
- pthread_detach(thread1);
- }
- while(1)
- {
- sleep(2);
- i++;
- printf("\n 第%d 次唤醒\n",i);
- pthread_mutex_lock(&lock);
- if(-1==pthread_cond_signal(&cond))
- {
- printf("pthread_cond_broadcast error!\n");
- }
- pthread_mutex_unlock(&lock);
- }
- return 0;
- }
