标签:pthread i++ nis message ace long nbsp std 实验
#include <bits/stdc++.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> #include <error.h> #include <sys/times.h> using namespace std; #define Producer 2 #define Customer 2 #define BufferSize 5 #define Threadnum 5 int Buffer[BufferSize]; pthread_t threads[Customer+Producer]; //the model of Customer sem_t canuseBuffers;//the messagebuffer free sem_t canuseProduct; pthread_mutex_t Mutex; int Point_in=0; int Point_out=0; int Customer_id = 0; int Producer_id = 0; void * Custome(void *args) { long num = (long)args; while(1) { sem_wait(&canuseProduct);//-- it pthread_mutex_lock(&Mutex); printf("pthread %d began to read!\n",num); Customer_id=Buffer[Point_out];//get a product Point_out = (Point_out+1)%BufferSize; sem_post(&canuseBuffers);//++ it pthread_mutex_unlock(&Mutex); printf("thread read over\n"); sleep(1); } return NULL; } void * Produce(void *args) { long num = (long)args; while(1) { sem_wait(&canuseBuffers);//--it pthread_mutex_lock(&Mutex); printf("pthread %d began to write\n",num); sem_post(&canuseProduct);//++it pthread_mutex_unlock(&Mutex); sleep(5); } return NULL; } int main() { sem_init(&canuseBuffers,0,BufferSize); sem_init(&canuseProduct,0,0); pthread_mutex_init(&Mutex,NULL); for(int i=0;i<Customer;i++) { int rc = 0; rc = pthread_create(&threads[i],NULL,Custome,(void *)i); if(rc) { printf("Error\n"); } printf("thread %d are request read\n",i); } for(int i=0;i<Customer+Producer;i++) { int rc = 0; rc = pthread_create(&threads[i],NULL,Produce,(void *)i); if(rc) { printf("Error!\n"); } printf("thread %d are request write\n",i); } for(int i=0;i<Customer+Producer;i++) { pthread_join(threads[i],NULL); } }
标签:pthread i++ nis message ace long nbsp std 实验
原文地址:https://www.cnblogs.com/masterchd/p/9129842.html