我试图std::thread用一个不带参数和返回的成员函数构造一个void.我无法弄清楚任何有效的语法 - 编译器无论如何都会抱怨.实现的正确方法是什么,spawn()以便返回std::thread执行的test()?
#include <thread>
class blub {
void test() {
}
public:
std::thread spawn() {
return { test };
}
};
Run Code Online (Sandbox Code Playgroud) 我想使用一个管理线程(或几个线程)的类.使用组合,这看起来像:
class MyClass{
private:
std::thread mythread;
void _ThreadMain();
public:
MyClass();
// other fields
}
Run Code Online (Sandbox Code Playgroud)
因为a的默认构造函数std::thread是没有意义的,我需要在MyClass构造函数中显式调用它:
MyClass::MyClass() : mythread(&MyClass::_ThreadMain,this) {}
Run Code Online (Sandbox Code Playgroud)
但是,在这种情况下,该_ThreadMain方法很可能在 MyClass构造之前执行,从而导致任何类型的奇怪行为.这显然是不安全的.我怎样才能解决这个问题?
一个明显的解决方案是使用指针std::thread代替,并添加另一个成员函数:
void MyClass::Start(){
// This time mythread is of type std::thread*
mythread = new std::thread(&MyClass::_ThreadMain,this); // One could use std::unique_pointer instead.
}
Run Code Online (Sandbox Code Playgroud)
这将启动该线程.在这种情况下,它将在构造类之后调用,这确实是安全的.
但是,我想知道是否有任何合理的解决方案可以让我不使用指针.感觉它应该是可能的某种方式(嘿,必须有一种方法来在构建一个类时启动一个线程!),但我无法想出任何不会引起麻烦的事情.
我考虑过使用一个条件变量,_ThreadMain等待构造函数完成它的工作,但是在构造类之前我不能使用它,对吧?(如果MyClass是派生类,这也没有用)
std::thread当类定义为模板时,无法将函数作为参数传递。
编译器:GCC 4.8.2 语言:C++11
代码:
//---------test.h-----------------------
#ifndef TEST_H
#define TEST_H
#include <iostream>
#include <thread>
using namespace std;
template <class T>
class test
{
public:
test();
void thr(T n);
void testThread();
};
#endif // TEST_H
//---------test.cpp-----------------------
#include "test.h"
template <class T>
test<T>::test()
{
}
template <class T>
void test<T>::thr(T n)
{
cout << n << endl;
}
template <class T>
void test<T>::testThread()
{
T n = 8;
thread t(thr, n);
t.join();
}
//---------main.cpp-----------------------
#include <iostream>
using namespace std;
#include "test.h" …Run Code Online (Sandbox Code Playgroud)