Smi*_*thy 33 c++ multithreading c++11
我正在进入C++ 11线程并遇到了问题.
我想将一个线程变量声明为全局并稍后启动它.
然而,我见过的所有例子似乎都是立即启动线程的
thread t(doSomething);
Run Code Online (Sandbox Code Playgroud)
我想要的是
thread t;
Run Code Online (Sandbox Code Playgroud)
并稍后启动该帖子.
我试过的是
if(!isThreadRunning)
{
thread t(readTable);
}
Run Code Online (Sandbox Code Playgroud)
但现在是块范围.所以我想声明t然后稍后启动线程,以便其他函数可以访问t.
谢谢你的帮助.
Sam*_*hik 44
std::thread默认构造函数实例化a std::thread而不启动或表示任何实际线程.
std::thread t;
Run Code Online (Sandbox Code Playgroud)
赋值运算符移动线程对象的状态,并将已分配的线程对象设置为其默认初始化状态:
t = std::thread(/* new thread code goes here */);
Run Code Online (Sandbox Code Playgroud)
这首先构造一个表示新线程的临时线程对象,将新线程表示传递给具有默认状态的现有线程对象,并将临时线程对象的状态设置为不代表任何正在运行的线程的默认状态.然后,临时线程对象被销毁,什么都不做.
这是一个例子:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我会给线程一个条件变量和一个名为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();
}
Run Code Online (Sandbox Code Playgroud)
编辑#2:在上面的代码中,变量theMutex、startRunning和cond_var必须可由两个线程访问。是否通过将它们设为全局变量或将它们封装在结构/类实例中来实现这一目标取决于您。