1:thread类:
我们使用thread类来进行线程的创建
构造函数:
- template <class function, class... Args>
- explicit thread(Fn&& function, Args&&... args);
其中function是线程调用的函数,args是function参数列表中的函数;
左值拷贝函数:
void thread::operator = (const thread& other) = delete;
很明显不支持左值引用的拷贝函数,但是右值拷贝函数存在;
join函数:
当我们主线程调用join函数时,主线程会等待子线程执行完毕,即被阻塞;
joinable函数:
检测线程是否可被joinable;
detach函数:
将子线程与主线程的关联分离,即detach后的子线程在后台独立运行,主线程没法获得子线程的控制权,且当主线程执行完成后子线程仍然可在运行;
- #include
- #include
-
- #include
// std::chrono::seconds - #include
// std::cout - #include
// std::thread, std::this_thread::sleep_for - #include
-
- void sleep1() {
- while (1) {
- Sleep(100);
- std::cout << "Working..." << std::endl;
- }
- }
- void sleep() {
- std::thread thSon(sleep1);
- std::cout << "Over" << std::endl;
- }
-
- int main() {
-
- std::thread thSon(sleep);
- thSon.join();
- int x; std::cin >> x;
- }
另外,让我们来看一个易错点:
- int main() {
-
- std::thread thSon;
- std::thread thSon_1(fun);
- thSon = thSon_1;//wrong
- thSon = std::thread(fun);//accpet
- thSon.join();
- }
wrong是用左值对其进行拷贝,但我们前面说了,左值拷贝函数已经被delete了
所以我们只能进行一个右值拷贝;
当主线程完成之前,定要讲所有附着在主线程上的子线程给脱离[detach]或者合作[join],否则报错,至于为什么这么干,这其实很好理解,因为主线程开了子线程,说明他们俩之间有逻辑关系,在这种逻辑关系被撤销或者完成前无意地切断这种逻辑是肥肠危险的!
detach后,仍然可能可以被主线程join进来,但要用joinable函数判断一下,防止报错;
右值拷贝并不会开出两个线程,因为右值拷贝是将右值的空间给被拷贝的对象,并没有出现new
出新的空间