课时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()能够得到线程IDthis

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);
相关文章
相关标签/搜索