Skip to content

第二章-线程管控.md

回到目录

2.1 线程的基本管控

  • std::join
  • std::thread

2.1.3

可以设计一个类,用RAII的编程技巧,析构函数调用线程join()

2.2 向线程函数传递参数

std::ref()

成员函数作为线程的函数例子

#include <iostream>
#include <thread>

class AA {
public:
    void get_sum(int a, int b) {
        std::cout << "sum = " << a + b << std::endl; 
    }
};

int main()
{
    AA a;
    std::thread t1(&AA::get_sum, &a, 10, 20);
    t1.join();

    return 0;
}

std::thread类的实例能够移动(movable)却不能复制(notcopyable),std::move转移线程所有权

2.3 移交线程归属权

std::thread支持移动操作的意义是,函数可以便捷地向外部转移线程的归属权,示例代码:

// 从函数内部返回std::thread对象
AA a;
std::thread thread_get_sum() {
    return std::thread(&AA::get_sum, &a, 10, 20);
}

// vecter利用移动语义生成多个线程
std::vecter<std::thread> threads;
threads.emplace_back(fun, i)

2.4 在运行时选择线程数量

TODO

2.5 识别线程

  • std::thread::id, thread.get_id()
  • std::this_thread::get_id()