知乎说《C++并发编程实战》这本书翻译的很烂,原书"C++ Concurrency in Action"不错。The C++ Standard Library: A Tutorial and Reference: 1136 pages, 太贵太厚了。试了几个 简单的例子。Stackoverflow(Why is "using namespace std;" considered bad practice?),但为了少打字我们还是用了。
// 生产者 消费者 cond_var
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <queue>
using namespace std;
mutex mtx;
condition_variable produce, consume;
queue<char> warehouse;
void consumer() {
// A unique lock manages a mutex object with unique ownership
unique_lock<mutex> lck(mtx); // locking initialization
// At the moment of blocking the thread, wait() automatically calls lck.unlock()
while (warehouse.empty()) consume.wait(lck);
// mtx was locked again
cout << warehouse.front(); warehouse.pop();
produce.notify_all();
// An unique_lock promises an unlocked status on destruction
}
void producer(int id) {
unique_lock<mutex> lck(mtx);
while (warehouse.size() >= 3) produce.wait(lck);
warehouse.push('A' + id);
consume.notify_all();
}
int main () {
enum { N = 10 };
thread c[N], p[N];
for (int i=0; i<N; ++i) c[i] = thread(consumer), p[i] = thread(producer, i);
for (int i=0; i<N; ++i) c[i].join(), p[i].join();
cout << endl << warehouse.size() << endl;
return 0;
}
// promise future
// If you want to store a future in a list, you need to use move() because it is not copyable.
#include <future>
#include <chrono>
using namespace std;
#include <stdio.h>
int square(int x) { // Just show passing parameters
puts("a"); this_thread::sleep_for(3s); // user-defined literals (since C++11)
puts("b"); scanf("%d", &x);
return x * x;
}
int main() {
/*future<int>*/auto fut = async(square, 10);
puts("c");
printf("%d\n", fut.get());
return 0;
}
// atomic
#include <atomic>
#include <vector>
using namespace std;
atomic<int> i;
struct BigFat {
BigFat(const BigFat&) {}
BigFat& operator=(const BigFat&) { return *this; }
vector<int> big, fat;
};
atomic<BigFat> bf; // error: atomic requires a trivially copyable type
int main() { return 0; }
// A mutex (mutual exlusion) allows us to enclose blocks of code that should only be
// executed in one thread at a time.
// Why join? "She joined her aunt in the sitting room.",
// "the point where the two roads join"
https://zhuanlan.zhihu.com/p/146534143
--
修改:billybear04 FROM 106.121.5.*
FROM 106.121.5.*