Linux 之 條件變數
正文
pthread_cond_init函式
pthread_cond_destroy函式
pthread_cond_wait函式
pthread_cond_timedwait函式
pthread_cond_signal函式
pthread_cond_broadcast函式
以上6 個函式的回傳值都是:成功回傳0, 失敗直接回傳錯誤號,
pthread_cond_init
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
引數:
cond: pthread_cond_t 型別的條件變數
attr: 屬性,默認傳NULL
也可以使用靜態初始化:
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_destroy
int pthread_cond_destroy(pthread_cond_t *cond);
pthread_cond_wait
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
引數:
cond:條件變數
mutex:互斥量
在第一次呼叫之前先給mutex上鎖,呼叫pthread_cond_wait函式會將鎖釋放,并阻塞直到被喚醒,被喚醒后對mutex上鎖成功后回傳,否則阻塞直到上鎖成功,
pthread_cond_timedwait
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
引數
abstime:絕對時間
struct timespec {
time_t tv_sec; // seconds 秒
long tv_nsec; //nanosecondes 納秒
}
阻塞超時后回傳,
pthread_cond_signal
int pthread_cond_signal(pthread_cond_t *cond);
喚醒至少一個條件變數,
pthread_cond_broadcast
int pthread_cond_broadcast(pthread_cond_t *cond);
喚醒全部的條件變數,
條件變數實作生產者消費者模型
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<errno.h>
#include<pthread.h>
#include<queue>
using namespace std;
pthread_mutex_t mutex;
pthread_cond_t cond;
queue<int>qu;
void str_error()
{
const char * str = strerror(errno);
write(STDERR_FILENO,str,sizeof(str));
exit(-1);
}
void* fun1(void* arg)
{
for(int i=0;i<1000;i++)
{
pthread_mutex_lock(&mutex);
qu.push(i);
printf("producer pushed %d into queue\n",i);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
return NULL;
}
void* fun2(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(qu.empty())
{
pthread_cond_wait(&cond,&mutex);
}
int i = qu.front();
qu.pop();
printf("consumer poped %d from queue\n",i);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
pthread_t producer,consumer;
if(pthread_mutex_init(&mutex,NULL) != 0)
str_error();
if(pthread_cond_init(&cond,NULL) != 0)
str_error();
if(pthread_create(&producer,NULL,fun1,NULL) != 0)
str_error();
if(pthread_create(&consumer,NULL,fun2,NULL) != 0)
str_error();
pthread_join(producer,NULL);
pthread_join(consumer,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/38183.html
標籤:其他
上一篇:2020-09-08課堂筆記
下一篇:VXlan深入解讀
