#include
#include
#include
#include
#include
using
namespace
std;
static
const
int kitemstoproduce = 20;//定義生產者能夠生產的最大產品個數
std::mutex stdoutmutex;//多執行緒標準輸出 同步鎖
struct itemrepository
gitemrepository; // 產品庫全域性變數,生產者和消費者操作該變數.
typedef
struct itemrepository itemrepository;
// 生產 產品
void produceitem(itemrepository &itemrepo, int item)
return !full;
});itemrepo.itemqueue.push_back(item); // 倉庫放入產品
itemrepo.repository_notempty.notify_all(); // 通知消費者倉庫不為空
lock.unlock(); // 釋放鎖
}// 消費 產品
int consumeitem(itemrepository &itemrepo)
return !empty;
});data = itemrepo.itemqueue.front();
itemrepo.itemqueue.pop_front();
itemrepo.repository_notfull.notify_all();
lock.unlock();
return data;
}// 生產者任務
void producertask()
}}// 消費者任務
void consumertask(int th_id)
}else
lock.unlock();
if (readytoexit)
break;
}}int main()
1 ^th item...
produce the
2 ^th item...
produce the
3 ^th item...
produce the
4 ^th item...
produce the
5 ^th item...
produce the
6 ^th item...
produce the
7 ^th item...
produce the
8 ^th item...
produce the
9 ^th item...
produce the
10 ^th item...
倉庫滿了,生產者等待中...thread id = 140649595565824
consume thread 1
the1^th item...
produce the
11 ^th item...
倉庫滿了,生產者等待中...thread id = 140649595565824
consume thread 2
the2^th item...
consume thread 4
the3^th item...
consume thread 3
the4^th item...
produce the
12 ^th item...
produce the
13 ^th item...
produce the
14 ^th item...
倉庫滿了,生產者等待中...thread id = 140649595565824
consume thread 1
the5^th item...
produce the
15 ^th item...
倉庫滿了,生產者等待中...thread id = 140649595565824
consume thread 2
the6^th item...
consume thread 4
the7^th item...
consume thread 3
the8^th item...
produce the
16 ^th item...
produce the
17 ^th item...
produce the
18 ^th item...
倉庫滿了,生產者等待中...thread id = 140649595565824
consume thread 1
the9^th item...
produce the
19 ^th item...
倉庫滿了,生產者等待中...thread id = 140649595565824
consume thread 2
the10^th item...
consume thread 4
the11^th item...
consume thread 3
the12^th item...
produce the
20 ^th item...
producer thread exit....
consume thread 1
the13^th item...
consume thread 2
the14^th item...
consume thread 4
the15^th item...
consume thread 3
the16^th item...
consume thread 1
the17^th item...
consume thread 2
the18^th item...
consume thread 4
the19^th item...
consume thread 3
the20^th item...
consumer thread 1
exit....
consumer thread 2
exit....
consumer thread 4
exit....
consumer thread 3
exit....
real
0m6.067s
user 0m0.004s
sys 0m0.052s
g++ main2.cpp -std=c++11 -lpthread
time ./a.out > my.log
生產者消費者 生產者與消費者模式
一 什麼是生產者與消費者模式 其實生產者與消費者模式就是乙個多執行緒併發協作的模式,在這個模式中呢,一部分執行緒被用於去生產資料,另一部分執行緒去處理資料,於是便有了形象的生產者與消費者了。而為了更好的優化生產者與消費者的關係,便設立乙個緩衝區,也就相當於乙個資料倉儲,當生產者生產資料時鎖住倉庫,不...
單生產者 多消費者模型
問題出處 生產者消費者問題 有乙個生產者在生產產品,這些產品將提供給若干個消費者去消費,為了使生產者和消費者能併發執行,在兩者之間設定乙個有多個緩衝區的緩衝池,生產者將它生產的產品放入乙個緩衝區中,消費者可以從緩衝區中取走產品進行消費,所有生產者和消費者都是非同步方式執行的,但它們必須保持同步,即不...
單生產者,單消費者
單個生產者和單個消費者 include include include include include include define buffer size 5 產品庫存大小 define product cnt 50 產品生產總數 struct product cons buffer void i...