C++ Concurrency in Action 02 线程管理

本文介绍了C++中线程管理的相关问题,包括如何避免将std::thread对象构造函数误解析为函数声明,提供了解决方法如使用额外括号或统一初始化语法。还讨论了线程安全问题,如防止异常时join不成功,可以使用RAII类确保析构时join。另外,介绍了detach在线程独立运行场景的应用,以及对于不可复制资源,如何通过move操作转移所有权。最后提到了使用scoped_thread确保线程资源的正确管理。
摘要由CSDN通过智能技术生成

定义std::thread对象:

1. 函数方式

#include <thread>
void do_some_work();
std::thread my_thread(do_some_work);

2. 对象方式

#include <iostream>
#include <thread>

class background_task
{
public:
    //重载()需要两个(),类比重载++, Test Test::operator++(int)
    void operator()()const
    {
        std::cout << "Hello\n";
    }
};

//background_task f;
//std::thread my_thread(f);

int main()
{
    background_task f;
    std::thread my_thread(f);
    my_thread.join();

    return 0;
}

定义std::thread对象的时候需要注意:

如果给std::thread对象的构造函数传入一个临时对象而不是一个正式定义的对象作为参数的时候,会被编译器解释成声明一个函数。如下:

std::thread my_thread(background_task());

会被当做声明一个函数my_thread,返回值为std::thread, 函数参数为函数指针background_task func (void),而不是定义一个函数对象。

declares a function my_thread that takes a single parameter (of type pointer to a function taking no parameters and returning a background_task object) and returns a std::thread object, rather than launching a new thread.

如何避免这种情况?

方法1: 将参数再用一个()括起来。

std::thread my_thread((background_task()));

the extra parentheses prevent interpretation as a function declaration, thus allowing my_thread to be declared as a variable of type std::

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值