Condition variables in Linux
text
pthread_cond_init function
pthread_cond_destroy function
pthread_cond_wait function
pthread_cond_timedwait function
pthread_cond_signal function
pthread_cond_broadcast function
The return values of the above 6 functions are: return 0 on success, and return error number directly on failure.
pthread_cond_init
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
Parameters :
cond: pthread_cond_t type condition variable
attr: attribute, default NULL
can also be used for static initialization:
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);
Parameters:
cond: condition variable
mutex: the mutex
locks the mutex before the first call, calling the pthread_cond_wait function will release the lock and block until awakened , After being awakened, the mutex will be successfully locked and returned, otherwise it will be blocked until the locking is successful.
pthread_cond_timedwait
int pthread_cond_timedwait (pthread_cond_t * restrict cond, pthread_mutex_t * restrict mutex, const struct timespec * restrict abstime);
Parameters
abstime: absolute time
struct {the timespec time_t the tv_sec; // seconds The second long tv_nsec; // nanosecondes ns } return after a timeout obstruction.
pthread_cond_signal
int pthread_cond_signal(pthread_cond_t *cond);
Wake up at least one condition variable.
pthread_cond_broadcast
int pthread_cond_broadcast(pthread_cond_t *cond);
Wake up all condition variables.
Condition variables implement producer consumer model
#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);
}