[cpp]view plain
copy
#include
#include
#define buffer_size 16 // 緩衝區數量
struct prodcons
; /* 初始化緩衝區結構 */
void init(struct prodcons *b)
/* 將產品放入緩衝區,這裡是存入乙個整數*/
void put(struct prodcons *b, int data)
/* 寫資料,並移動指標 */
b->buffer[b->writepos] = data;
b->writepos++;
if (b->writepos >= buffer_size)
b->writepos = 0;
/* 設定緩衝區非空的條件變數*/
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
/* 從緩衝區中取出整數*/
int get(struct prodcons *b)
/* 讀資料,移動讀指標*/
data = b->buffer[b->readpos];
b->readpos++;
if (b->readpos >= buffer_size)
b->readpos = 0;
/* 設定緩衝區未滿的條件變數*/
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
} /* 測試:生產者執行緒將1 到10000 的整數送入緩衝區,消費者線
程從緩衝區中獲取整數,兩者都列印資訊*/
#define over ( - 1)
struct prodcons buffer;
void *producer(void *data)
put(&buffer, over);
return null;
} void *consumer(void *data)
return null;
} int main(void)
生產者消費者執行緒
include include include includeusing namespace std typedef int semaphore 訊號量是一種特殊的整型變數 const int size of buffer 5 緩衝區長度 const unsigned short producers...
生產者消費者執行緒
該簡單生產者 消費者執行緒,屬於本人學習過程中的一段練習 如有不足,請指點 package com.lanqiao.demo3 author 大廣子 類說明 簡單的生產者,消費者執行緒 public class threadptcs catch interruptedexception e 退出 s...
Linux多執行緒 生產者消費者
生產者消費者問題 這是乙個非常經典的多執行緒題目,題目大意如下 有乙個生產者在生產產品,這些產品將提供給若干個消費者去消費,為了使生產者和消費者能併發執行,在兩者之間設定乙個有多個緩衝區的緩衝池,生產者將它生產的產品放入乙個緩衝區中,消費者可以從緩衝區中取走產品進行消費,所有生產者和消費者都是非同步...