#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
/**
*int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t * cond_attr);
*int pthread_cond_signal(pthread_cond_t *cond);
*int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t * mutex);
*int pthread_cond_broadcast(pthread_cond_t *cond);
*int pthread_cond_timewait(pthread_cond_t *cond, pthread_mutex_t * mutex, const struct timespec * abstime);
*int pthread_cond_destroy(pthread_cond_t *cond);
*/
void * pthread_odd_function(void * arg);
void * pthread_even_function(void * arg);
pthread_mutex_t work_mutex;
pthread_cond_t work_cond;
#define MAX_COUNT 10
int count = 0;
int main(int argc, char const *argv[])
{
pthread_t pthread_odd;
pthread_t pthread_even;
pthread_attr_t pthread_attr;
// void * result;
int res;
res = pthread_attr_init(&pthread_attr);//init pthread attribute,step 1
if (res != 0)
{
perror("pthread_attr_init failed!");
exit(EXIT_FAILURE);
}
res = pthread_cond_init(&work_cond,NULL);
if (res != 0)
{
perror("pthread_cond_init failed!");
exit(EXIT_FAILURE);
}
res = pthread_mutex_init(&work_mutex,NULL);
if (res != 0)
{
perror("pthread_mutex_init failed!");
exit(EXIT_FAILURE);
}
pthread_attr_setdetachstate(&pthread_attr,PTHREAD_CREATE_DETACHED);//design pthread attribute step 2
res = pthread_create(&pthread_odd,&pthread_attr,pthread_odd_function,NULL);//step 3
if (res != 0)
{
perror("pthread_create failed!");
exit(EXIT_FAILURE);
}
res = pthread_create(&pthread_even,&pthread_attr,pthread_even_function,NULL);
if (res != 0)
{
perror("pthread_create failed!");
exit(EXIT_FAILURE);
}
while(count < MAX_COUNT);//wait the two sons threads finished
pthread_mutex_destroy(&work_mutex);
pthread_cond_destroy(&work_cond);
pthread_exit(NULL);
return 0;
}
void * pthread_odd_function(void *arg)//step 4
{
pthread_mutex_lock(&work_mutex);
while(count < MAX_COUNT)
{
if (count % 2 == 1)
{
++count;
printf("the odd count is : %d\n", count);
pthread_cond_signal(&work_cond);//in order to release the thread of even
}
else
pthread_cond_wait(&work_cond,&work_mutex);//the pthread is blocked,wait for the condition
}
pthread_mutex_unlock(&work_mutex);
}
void * pthread_even_function(void *arg)//step 5
{
pthread_mutex_lock(&work_mutex);
while(count < MAX_COUNT)
{
if (count % 2 == 0)
{
++count;
printf("the even count is : %d\n", count);
pthread_cond_signal(&work_cond);//in order to release the thread of odd
}
else
pthread_cond_wait(&work_cond,&work_mutex);//wait the condition satisfied
}
pthread_mutex_unlock(&work_mutex);
}
mutex是为了控制线程共享临界资源count,cond是为了在线程不满足条件的情况下,触发另一个线程,防止死锁