《C++併發程式設計實戰》讀書筆記(1)
這兩天開始看《C++併發程式設計實戰》一書,感覺受益匪淺啊!
按照書中的同步併發操作(第四章)的內容,嘗試編寫執行緒安全的佇列,模擬固定採集時間和不確定處理時間下的佇列行為,供大家參考。
用到的C++多執行緒相關的主要內容為:mutex類(鎖物件),lock_guard模板(實現鎖物件的RAII用法),unique_lock模版,condition_variable類(用於程序間等待與喚醒)
另外,書中提供了非常好的技巧,如mutex物件在類中設定為mutable(可變),以用於靜態成員函式等。
上程式碼,執行緒安全佇列部分參考書上寫的,僅供大家學習交流。
這個是threadsafe_queue的標頭檔案:
#ifndef SQUEUE
#define SQUEUE
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
template<typename T>
class threadsafe_queue{
private:
mutable std::mutex mut;
std::queue<T> data_queue;
std::condition_variable data_cond;
public:
threadsafe_queue() = default;
threadsafe_queue(const threadsafe_queue &other){
std::lock_guard<std::mutex> lk(other.mut);
data_queue = other.data_queue;
}
threadsafe_queue &operator=(const threadsafe_queue &other){
std::lock_guard<std::mutex> lk(other.mut);
data_queue = other.data_queue;
}
void push(T new_val){
std::lock_guard<std::mutex> lk(mut);
data_queue.push(new_val);
data_cond.notify_all();
}
void wait_and_pop(T &value){
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this](){return !data_queue.empty(); });
value = data_queue.front();
data_queue.pop();
}
std::shared_ptr<T> wait_and_pop(){
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this](){return !data_queue.empty()});
std::shared_ptr<T> ptr(std::make_shared<T>(data_queue.front()));
data_queue.pop();
return ptr;
}
bool try_pop(T &value){
std::lock_guard<std::mutex> lk(mut);
if (data_queue.empty())
return false;
value = data_queue.front();
data_queue.pop();
return true;
}
std::shared_ptr<T> try_pop(){
std::lock_guard<std::mutex> lk(mut);
if (data_queue.empty())
return std::shared_ptr<T>();
std::shared_ptr<T> ptr(std::make_shared<T>(data_queue.front()));
data_queue.pop();
return ptr;
}
bool empty() const{
std::lock_guard<std::mutex> lk(mut);
return data_queue.empty();
}
int size() const{
std::lock_guard<std::mutex> lk(mut);
return data_queue.size();
}
};
#endif
測試程式碼:
#include "S_queue.h"
#include <vector>
#include <iostream>
#include <thread>
#include <string>
#include <random>
#include <condition_variable>
using namespace std;
void fun1(int value, threadsafe_queue<int> &iq){
uniform_int_distribution<int> u(-100, 100);
default_random_engine e(time(0));
for (int i = 0; i != value; --i){
this_thread::sleep_for(chrono::milliseconds(100));
iq.push(u(e));
}
}
void fun2(int value, threadsafe_queue<int> &iq){
uniform_int_distribution<int> u(90, 105);
default_random_engine e(time(0));
for (int i = 0; i != value; --i){
this_thread::sleep_for(chrono::milliseconds(u(e)));
int val;
cout << "Size: " << iq.size() << " —— ";
iq.wait_and_pop(val);
cout << "Value: " << val << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string line;
threadsafe_queue<int> iq;
int num;
cin >> num;
thread t1(fun1, num, ref(iq)), t2(fun2, num, ref(iq));
t1.join();
t2.detach();
cin >> line;
return 0;
}