课时4 线程传参详解,detach()大坑,成员函数做线程函数

线程传参

void myprint(int a)
{
    cout << "此时在子线程中" << endl;
    cout << "a = " << a  << endl;
}

int main(int argc, char** argv)
{
    int a = 1;

    thread myjob(myprint, a);

    cout << "此时在主线程中" << endl;
    return 0;
}

detach()的坑

  • 使用detach()时会有这么一个问题:因为子线程与主线程分离了,如果子线程的可调用对象使用了main()里的变量且主线程又先结束了,则会在子线程中就使用了根本不存在的东西,就会产生不可预测现象,尤其是当可调用对象的参数为引用或指针类型

  • 参数中有类的对象时,如果想通过隐式转换传入类对象很可能会出现错误,最好老老实实传入类对象或构造好类对象传入代码中的std::this_thread::get_id()可以获得线程ID

class A
{
public:
    A(int i):myi(i) { cout << "构造函数" << std::this_thread::get_id() << endl; }
    A(const A& a):myi(a.myi) { cout << "拷贝构造函数" << std::this_thread::get_id() << endl; }

    void operator()() { cout << "此时在子线程中" << std::this_thread::get_id() << endl; }

    ~A() { cout << "析构函数" << std::this_thread::get_id() << endl; }
private:
    int myi;
};

void myprint(const int& a, const A& b)
{
    cout << "此时在子线程中" << std::this_thread::get_id() << endl;
}

int main(int argc, char** argv)
{
    int a = 1;
    int& b = a;
    A c(a);
    thread myjob(myprint, a, c);
    //thread myjob(myprint, a, A(a));构造好类的临时对象传入
    //thread myjob(myprint, a, a);千万不要有这种操作,碰上detach就完了,在打印出来的线程id中可以看到将a转换为类的对象是在子线程中完成的,如果用了detach且主线程又先结束了,那就会使用一个不存在的变量

    myjob.join();

    cout << "此时在主线程中" << std::this_thread::get_id() << endl;
    return 0;
  • 当使用了引用传递(然而现在看来引用类型都必须是constthread还是会用值传递的方式传入可调用对象,比如上面的那个类,所以当在子线程中修改变量时主线程不会同步修改,此时加个std::ref()可以解决,他就可以真正的按引用传递的方式
class A
{
public:
...
    void change() const { myi = 199; }

private:
    mutable int myi;
};

void myprint(const int& a, const A& b)
{
    b.change();
    cout << "此时在子线程中" << std::this_thread::get_id() << endl;
}

int main(int argc, char** argv)
{
    int a = 1;
    int& b = a;
    A c(a);
    thread myjob(myprint, a, std::ref(c));

    myjob.join();

    cout << "此时在主线程中" << std::this_thread::get_id() << endl;
    return 0;

一些其他的线程入口

  • unique_ptr类型智能指针传递需使用std::move()
void myprint(unique_ptr<int> a)
{
    cout << *a << endl;
    cout << "此时在子线程中" << std::this_thread::get_id() << endl;
}

int main(int argc, char** argv)
{
    unique_ptr<int> d(new int(100));
    thread myjob(myprint, std::move(d));
  • 使用成员函数作为可调用对象
    void change(int ab) { cout << ab << "此时在子线程中" << std::this_thread::get_id() << endl; }

    int a = 1;
    int& b = a;
    A c(a);
    thread myjob(&A::change, c, 100);
  • 用类作为可调用对象且有参数的情况
    void operator()(int ab) { cout << ab << "此时在子线程中" << endl; }

    A a;
    thread myjob(a, 100);

转载于:https://www.cnblogs.com/Anthony-ling/p/11440699.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值