首页 > 编程语言 > 详细

线程参数传递类对象

时间:2020-03-18 22:41:49      阅读:54      评论:0      收藏:0      [点我收藏+]

为什么会调用一个传递一个类对象呢,这是一个我在写线程池的时候遇到的一个问题,当我把工作函数写成一个函数类的时候(重载operator()())线程传递参数的时候与普通函数出现了差别,当我像传递普通函数那样传递的时候,怎么也不能编译通过,于是在查找相关资料解决了这个问题,在这里记录一下

//...头文件省略
void func() {
    std::cout << "thread in func" << std::endl;
}

class functor {
    int m_id;
public:
    functor(const int id) : m_id(id) { }
    void operator() () {
        std::cout << "thread in functor" << m_id << std::endl;
    }
};

int main() {
int x = 11;
std::thread t(func);  // OK
// std::thread t1(functor(x)) // not ok
std::thread t1( (functor(x)) ); // OK
t.join();
t1.join(); 
return 0;
}

至于为什么要加一对括号,看其他说法是这和c++函数声明有关,具体有时间再去深究。

线程参数传递类对象

原文:https://www.cnblogs.com/codemeta-2020/p/12520495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!