pthread_cond_wait and pthread_cond_signal


                                    pthread_cond_wait and pthread_cond_signal

 

函数定义
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t * mutex,const struct timespec *abstime);
int pthread_cond_signal(pthread_cond_t *cond);

pthread_cond_wait 等待条件变量满足条件才执行,否则挂起
调用时执行如下步骤
relase mutex, 当其他线程调用pthread_cond_signal()或pthread_cond_broadcast,唤醒该线程,
pthread_cond_wait()再次获得该mutex,然后返回

pthread_cond_timedwait等待到指定时间,如果还没有发生返回ETIMEOUT

pthread_cond_signal()每次仅唤醒一个线程,如果要唤醒多个,使用pthread_cond_broadcast

 

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

static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int sharedvariable;

static void *thread_func(void *arg)
{

  while (1)
  {
    pthread_mutex_lock(&mut);
    pthread_cond_wait(&cond, &mut);
    printf("Read sharedvariable=%d\n", sharedvariable);
    pthread_mutex_unlock(&mut);
    pthread_mutex_unlock(&mut);
   }
   return 0;
 }
      
int main(void)
{
 pthread_t tid;
 int i;

 pthread_create(&tid, NULL, thread_func, NULL);
 
 sleep(2);
 for (i = 0; i < 10; i++)
 {
   pthread_mutex_lock(&mut);
   sharedvariable = i;
   printf("set sharedvariable=%d\n",sharedvariable);
   pthread_cond_signal(&cond);
   pthread_mutex_unlock(&mut);
   sleep(1);
 }
 pthread_cancel(tid);
 pthread_join(tid, NULL);
 printf("exiting\n");
 return 0;

}
编译
gcc -c a.c
gcc -o a a.o -lpthread

 

int pthread_join(pthread_t thread, void **retval);   
函数pthread_join用来等待一个线程的结束。 以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值