#include <iostream>
#include "Configure.h"
#include "Utils.h"
#include <queue>
using namespace std;
queue<int> product;
pthread_mutex_t mutex;
void *Produce(void *args)
{
int i;
for(i = 0; i < 10; i++){
pthread_mutex_lock(&mutex);
product.push(i);
CC_NOTICE("Produce %d", i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(NULL);
}
void *Consume(void *args)
{
int i;
for(i = 0; i < 10; i++){
pthread_mutex_lock(&mutex);
if(product.empty()){
pthread_mutex_unlock(&mutex);
continue;
}
CC_NOTICE("Consume %d", product.front());
product.pop();
pthread_mutex_unlock(&mutex);
sleep(2);
}
pthread_exit(NULL);
}
int main()
{
pthread_t proID, conID;
pthread_mutex_init(&mutex, NULL);
int ret;
ret = pthread_create(&proID, NULL, Produce, NULL);
if(ret != 0){
CC_FATAL("Create thread error");
exit(1);
}
ret = pthread_create(&conID, NULL, Consume, NULL);
if(ret != 0){
CC_FATAL("Create thread error");
exit(1);
}
pthread_join(proID, NULL);
pthread_join(conID, NULL);
return 0;
}
linux多线程 -- 互斥量
最新推荐文章于 2024-06-04 14:50:57 发布