#include <iostream>SYzLinux联盟 #include <pthread.h>SYzLinux联盟 #include <sys/time.h>SYzLinux联盟 using namespace std;SYzLinux联盟 SYzLinux联盟 int shareVal = 0;SYzLinux联盟 SYzLinux联盟 pthread_cond_t qready = PTHREAD_COND_INITIALIZER;SYzLinux联盟 pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;SYzLinux联盟 SYzLinux联盟 void *SYzLinux联盟 consumer(void* arg)SYzLinux联盟 {SYzLinux联盟 for (;;) {SYzLinux联盟 pthread_mutex_lock(&qlock);SYzLinux联盟 SYzLinux联盟 while(0 == shareVal) { /* No resource available, then wait */SYzLinux联盟 pthread_cond_wait(&qready, &qlock);SYzLinux联盟 }SYzLinux联盟 SYzLinux联盟 cout << "current shareVal = " << shareVal << endl;SYzLinux联盟 shareVal--;SYzLinux联盟 SYzLinux联盟 pthread_mutex_unlock(&qlock);SYzLinux联盟 }SYzLinux联盟 return ((void *)1);SYzLinux联盟 }SYzLinux联盟 SYzLinux联盟 void SYzLinux联盟 producer(void)SYzLinux联盟 {SYzLinux联盟 pthread_mutex_lock(&qlock);SYzLinux联盟 shareVal++;SYzLinux联盟 pthread_mutex_unlock(&qlock);SYzLinux联盟 pthread_cond_signal(&qready); /* resource is available, awake the consumer thread */SYzLinux联盟 }SYzLinux联盟 SYzLinux联盟 int main()SYzLinux联盟 {SYzLinux联盟 int err;SYzLinux联盟 pthread_t tid1;SYzLinux联盟 void *tret;SYzLinux联盟 SYzLinux联盟 err = pthread_create(&tid1, NULL, consumer, NULL);SYzLinux联盟 if (err != 0) {SYzLinux联盟 cout << "cant create thread" << endl;SYzLinux联盟 exit(1);SYzLinux联盟 }SYzLinux联盟 SYzLinux联盟 /*SYzLinux联盟 err = pthread_join(tid1, &tret);SYzLinux联盟 if (err != 0) {SYzLinux联盟 cout << "can't join" << endl;SYzLinux联盟 exit(1);SYzLinux联盟 }SYzLinux联盟 */SYzLinux联盟 SYzLinux联盟 for (int i = 0; i < 5; i++) {SYzLinux联盟 cout << "i = " << i << endl;SYzLinux联盟 producer();SYzLinux联盟 sleep(1);SYzLinux联盟 }SYzLinux联盟 SYzLinux联盟 pthread_mutex_destroy(&qlock);SYzLinux联盟 return 0;SYzLinux联盟 }SYzLinux联盟
|