-
#define _GNU_SOURCE
-
#include <unistd.h>
-
#include <pthread.h>
-
-
#include <stdlib.h>
-
#include <stdio.h>
-
-
//static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
-
// 这里虽然是 P/V ,但是用 cond 确实更方便。
-
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
-
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
-
-
int i = 0;
-
-
void get ( )
-
{
-
pthread_mutex_lock (&mutex );
-
while ( i == 0 ) // 队列下限
-
pthread_cond_wait (&cond, &mutex ); // 唤醒其它线程进行检测。
-
-
--i;
-
pthread_cond_signal (&cond );
-
-
pthread_mutex_unlock (&mutex );
-
}
-
-
void put ( )
-
{
-
pthread_mutex_lock (&mutex );
-
while ( i == 3 ) // 队列上限
-
pthread_cond_wait (&cond, &mutex );
-
-
++i;
-
pthread_cond_signal (&cond ); // 唤醒其它线程
-
-
pthread_mutex_unlock (&mutex );
-
}
-
-
void *thf ( void *arg )
-
{
-
while ( 1 )
-
{
-
put ( );
-
}
-
}
-
-
int main ( )
-
{
-
pthread_t tid;
-
pthread_create (&tid, NULL, thf, NULL );
-
-
sleep ( 3 );
-
while ( 1 )
-
get ( );
-
}
线程间通讯《代码》pthread_cond_t
本文介绍了一个使用pthread条件变量和互斥锁实现线程间同步的经典案例。通过定义一个简单的队列,当队列为空或满时,消费者或生产者线程将被阻塞,直到条件满足。此例展示了如何利用条件变量来通知等待线程,从而实现高效且可靠的线程间通信。

被折叠的 条评论
为什么被折叠?



