【发布时间】:2017-01-16 08:47:12
【问题描述】:
我有一个类,它有一个需要连续运行但也能够接收用户输入的方法。所以我想我会使用线程单独运行该方法。
代码看起来像这样(只是主干):
class SystemManager
{
private:
int command;
bool commandAcK;
bool running;
//other vars
public:
SystemManager()
{
//initialisation
}
void runningAlgorithm()
{
while (running)
{
if (commandAcK)
{
//solve command
}
//run algorithm
//print results
}
}
void readCmd()
{
cin >> command;
commandAcK = true;
}
};
int main()
{
SystemManager *SM = new SystemManager;
thread tRunning = SM->runningAlgorithm();
}
现在错误如下所示:
不存在合适的构造函数来将“void”转换为“std::thread”
错误 C2440 'initializing':无法从 'void' 转换为 'std::thread'
我找到了一个新方法,它没有给我任何错误
std::thread tRunning(&SystemManager::runningAlgorithm, SystemManager());
我不明白的第一件事是这个方法不使用类的实例,只是使用泛型函数。如何将其链接到特定实例?我需要它,以便它可以读取变量的值。
其次SystemManager前面的"&"是做什么的?
(&SystemManager::runningAlgorithm)
第三,有没有更好的方法呢?你有什么想法吗?
提前谢谢你。
【问题讨论】:
标签: c++ multithreading oop methods