我正在尝试使用一个不带参数并返回void的成员函数来构造一个std::thread。我找不出任何可以工作的语法--不管怎样编译器都会报错。实现spawn()使其返回执行test()的std::thread的正确方法是什么
#include <thread>
class blub {
void test() {
}
public:
std::thread spawn() {
return { test };
}
};发布于 2012-05-20 21:07:10
#include <thread>
#include <iostream>
class bar {
public:
void foo() {
std::cout << "hello from member function" << std::endl;
}
};
int main()
{
std::thread t(&bar::foo, bar());
t.join();
}编辑:核算你的编辑,你必须这样做:
std::thread spawn() {
return std::thread(&blub::test, this);
}更新:我想解释更多的观点,其中一些也在评论中讨论过。
上述语法根据调用定义(§20.8.2.1)定义:
定义INVOKE (f,t1,t2,...,tN)如下:
对类型T的对象的引用或对
从T派生的类型;
我想指出的另一个普遍事实是,默认情况下,线程构造函数将复制传递给它的所有参数。这样做的原因是,参数可能需要比调用线程更长的时间,复制参数可以保证这一点。相反,如果您希望真正传递引用,则可以使用由std::ref创建的std::reference_wrapper。
std::thread (foo, std::ref(arg1));通过这样做,您可以保证,当线程对参数进行操作时,您将保证参数仍然存在。
请注意,上面提到的所有内容也可以应用于std::async和std::bind。
发布于 2015-08-24 15:31:53
下面是一个完整的示例
#include <thread>
#include <iostream>
class Wrapper {
public:
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
std::thread member1Thread() {
return std::thread([=] { member1(); });
}
std::thread member2Thread(const char *arg1, unsigned arg2) {
return std::thread([=] { member2(arg1, arg2); });
}
};
int main(int argc, char **argv) {
Wrapper *w = new Wrapper();
std::thread tw1 = w->member1Thread();
std::thread tw2 = w->member2Thread("hello", 100);
tw1.join();
tw2.join();
return 0;
}使用g++编译会产生以下结果
g++ -Wall -std=c++11 hello.cc -o hello -pthread
i am member1
i am member2 and my first arg is (hello) and second arg is (100)发布于 2017-11-18 16:32:52
@hop5和@RnMss建议使用C++11 lambda,但是如果你处理指针,你可以直接使用它们:
#include <thread>
#include <iostream>
class CFoo {
public:
int m_i = 0;
void bar() {
++m_i;
}
};
int main() {
CFoo foo;
std::thread t1(&CFoo::bar, &foo);
t1.join();
std::thread t2(&CFoo::bar, &foo);
t2.join();
std::cout << foo.m_i << std::endl;
return 0;
}输出
2来自this answer的重写样本将是:
#include <thread>
#include <iostream>
class Wrapper {
public:
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
std::thread member1Thread() {
return std::thread(&Wrapper::member1, this);
}
std::thread member2Thread(const char *arg1, unsigned arg2) {
return std::thread(&Wrapper::member2, this, arg1, arg2);
}
};
int main() {
Wrapper *w = new Wrapper();
std::thread tw1 = w->member1Thread();
tw1.join();
std::thread tw2 = w->member2Thread("hello", 100);
tw2.join();
return 0;
}https://stackoverflow.com/questions/10673585
复制相似问题