⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 monitor.cpp

📁 linux下多线程实现生产者消费者及用并行算法求圆周率等经典算法
💻 CPP
字号:
#include <iostream>#include <pthread.h>#include <stdio.h>#include <unistd.h>using namespace std;#define QSIZE 8class monitor {private:     pthread_cond_t full; /* count the number of characters in the queue */     pthread_cond_t empty;/* count the number of empty slots */     pthread_mutex_t m;   /* implements the critical section */     unsigned int iBuf;   /* the tail of the circular queue */     unsigned int oBuf;   /* the head of the circular queue */     int count;           /* count characters */     char buf [QSIZE];    /* the circular queue */	public:     monitor() 	  {	       oBuf = 0; iBuf = 0; count=0;      /* head and tail match when queue empty */	       pthread_cond_init(&full, NULL);   /* no characters stored yet */	       pthread_cond_init(&empty, NULL);  /* all character slots are empty */	       pthread_mutex_init(&m, NULL);	  }     ~monitor() 	  {	       pthread_mutex_destroy(&m);	  }     void put(char ch) /* add "ch" to circular queue; wait if full */	  {	       pthread_mutex_lock(&m);	       while (count >= QSIZE) pthread_cond_wait(&empty, &m); /* is there an empty slot? */	       buf[iBuf] = ch;              /* store the character */	       iBuf = (iBuf+1) % QSIZE;     /* increment to QSIZE, then reset to 0 */	       cout << "put to buf[" << iBuf << "]" << endl;	       count++;	       pthread_cond_signal(&full); /* a new character is available */	       pthread_mutex_unlock(&m);	  }     char get() /* remove "ch" from queue; wait if empty */	  {	       char ch;	       pthread_mutex_lock(&m);	       while (count <= 0) pthread_cond_wait(&full, &m); /* is a character present? */	       ch = buf[oBuf];              /* retrieve from the head of the queue */	       oBuf = (oBuf+1) % QSIZE;	       cout << "get from buf[" << oBuf << "]" << endl;	       count--;	       pthread_cond_signal(&empty); /* signal existence of new empty slot */	       pthread_mutex_unlock(&m);	       return ch;	  }};void *producer(void *arg){     monitor *mon = (class monitor *)arg;     while (1) { mon->put('a'); sleep(1); }     return NULL;}void *consumer(void *arg){     monitor *mon = (class monitor *)arg;     while (1) { mon->get(); sleep(1); }     return NULL;}int main(){     monitor *mon = new monitor;     pthread_t tid[3];     void *retval;	     pthread_create(&tid[0], NULL, producer, (void*)mon);     pthread_create(&tid[1], NULL, producer, (void*)mon);     pthread_create(&tid[2], NULL, consumer, (void*)mon);     pthread_join(tid[0], &retval);     pthread_join(tid[1], &retval);     pthread_join(tid[2], &retval);	     delete mon;     return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -