我遇到了C++11线程,遇到了一个问题。
我希望将线程变量声明为全局变量,并在稍后启动它。
然而,我所见过的所有示例似乎都是立即启动线程的,例如
thread t(doSomething);我想要的是
thread t;并稍后启动该线程。
我试过的是
if(!isThreadRunning)
{
thread t(readTable);
}但现在t是块作用域。所以我想声明t,然后稍后启动线程,这样t就可以被其他函数访问了。
谢谢你的帮助。
发布于 2014-08-27 19:02:22
std::thread的默认构造函数在不启动或表示任何实际线程的情况下实例化std::thread。
std::thread t;赋值运算符移动线程对象的状态,并将赋值自线程对象设置为其默认初始化状态:
t = std::thread(/* new thread code goes here */);这首先构造表示新线程的临时线程对象,将新线程表示转移到具有默认状态的现有线程对象中,并将临时线程对象的状态设置为不表示任何正在运行的线程的默认状态。然后,临时线程对象被销毁,什么也不做。
下面是一个例子:
#include <iostream>
#include <thread>
void thread_func(const int i) {
std::cout << "hello from thread: " << i << std::endl;
}
int main() {
std::thread t;
std::cout << "t exists" << std::endl;
t = std::thread{ thread_func, 7 };
t.join();
std::cout << "done!" << std::endl;
}发布于 2014-08-27 18:54:25
我将为线程提供一个条件变量和一个名为startRunning的布尔值(最初设置为false)。实际上,您可以在创建线程时立即启动线程,但是它要做的第一件事就是挂起自己(使用condition_variable),然后仅当condition_variable从外部发出信号(并且startRunning标志设置为true)时才开始处理其实际任务。
编辑:伪代码:
// in your worker thread
{
lock_guard l( theMutex );
while ( ! startRunning )
{
cond_var.wait( l );
}
}
// now start processing task
// in your main thread (after creating the worker thread)
{
lock_guard l( theMutex );
startRunning = true;
cond_var.signal_one();
}编辑#2:在上面的代码中,两个线程都必须可以访问变量theMutex、startRunning和cond_var。您是通过使它们成为全局的还是通过将它们封装在结构/类实例中来实现这一点,这取决于您。
发布于 2014-08-27 19:07:32
没有创建线程“挂起”的“标准”,我想这就是您想要使用C++线程库做的事情。因为并不是每个有线程的平台都支持它,所以C++应用编程接口中也没有它。
std::thread对象)。您可以这样做,并在以后将其附加到一个函数,以便在新线程中run该函数。https://stackoverflow.com/questions/25524775
复制相似问题