C++11提供了新的thread接口的封装,终于统一了不同平台不同的底层接口。
-
创建一个线程
#include <iostream> #include <thread> // ① using namespace std; // ② void hello() { // ③ cout << "Hello World from new thread." << endl; } int main() { thread t(hello); // ④ t.join(); // ⑤ return 0; }
-
如何给线程传递参数
void hello(string name) { cout << "Welcome to " << name << endl; } int main() { thread t(hello, "https://paul.pub"); t.join(); return 0; }
join与detach
加锁mutex
如果要加多把锁的话,注意加锁的顺利,避免deadlock的坑
条件变量 wait 和 notify
发现这个人写的更好,可以移步到这里:
https://paul.pub/cpp-concurrency/
https://mp.weixin.qq.com/s/-kizIk3ZXqu7UNqAb3QlQw