知乎说《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; }
【 在 billybear04 (billybear04) 的大作中提到: 】 : 知乎说《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> : ................... -- FROM 112.47.122.*
【 在 billybear04 的大作中提到: 】 : 知乎说《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> : ................... 并发编程哪个都不好学。 -- FROM 123.118.54.*