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的