C++11并发编程

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容