#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <cstring>
#include <iostream>
using namespace std;
#define THREAD_NUMBER 2
/* 初始化條件變量*/
static pthread_cond_t cond= PTHREAD_COND_INITIALIZER;
/* 初始化mutex*/
static pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
void* thread1(void *arg)
{
int ret;
pthread_mutex_lock(&mutex);
printf("thread1 locked the mutex\n");
printf("thread1 is waiting for condition signal...\n");
cout <<"cond:"<<cond<<endl;
ret = pthread_cond_wait(&cond, &mutex);
printf("thread1 received condition signal!\n");
pthread_mutex_unlock(&mutex);
sleep(1);
printf("thread1 unlocked the mutex with ret: %d\n",ret);
pthread_exit(0);
}
void* thread2(void *arg)
{
int i = 0,ret;
struct timeval old, now;
gettimeofday(&old,NULL);
now = old;
pthread_mutex_lock(&mutex);
printf("thread2 locked the mutex\n");
/* 休眠5 秒鐘*/
while (now.tv_sec-old.tv_sec< 5) {
sleep(1);
gettimeofday(&now,NULL);
i++;
printf("thread2 sleep %d seconds\n", i);
}
printf("thread1 calls pthread_cond_signal...\n");
/* 啟動等待條件變量cond的其他線程*/
ret = pthread_cond_signal(&cond);
cout <<"cond:"<<&cond<<endl;
pthread_mutex_unlock(&mutex);
printf("thread2 unlocked the mutex with ret: %d\n",ret);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i;
int ret_val;
pthread_mutex_init(&mutex,NULL);
pthread_t pt[THREAD_NUMBER];
memset(pt,0,THREAD_NUMBER);
ret_val = pthread_create(&pt[0], NULL, thread1, NULL);
if (ret_val != 0 ) {
printf("pthread_create error!\n");
exit(1);
}
sleep(1);
ret_val = pthread_create(&pt[1], NULL, thread2, NULL);
if (ret_val != 0 )
{
printf("pthread_create error!\n");
exit(1);
}
for (i = 0; i < THREAD_NUMBER; i++)
{
ret_val = pthread_join(pt[i], NULL);
if (ret_val != 0)
{
printf("pthread_join error!\n");
exit(1);
}
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}