在C ++中延迟启动一个线程11

编程入门 行业动态 更新时间:2024-10-11 13:20:57
本文介绍了在C ++中延迟启动一个线程11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我进入C ++ 11线程并遇到了一个问题。

我想将一个线程变量声明为全局变量并稍后启动。 / p>

然而,我看到的所有例子似乎立即启动线程,例如

thread t(doSomething);

我想要的是

thread t;

并稍后开始执行。

我尝试的是

if(!isThreadRunning) { thread t(readTable); }

但现在t是块范围。所以我想声明t,然后再启动线程,以便t可以访问其他函数。

感谢任何帮助。

< c> std :: thread 的默认构造函数实例化一个 std :: thread / code>,无需启动或表示任何实际的线程。

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 {th​​read_func,7}; t.join(); std :: cout<< 完成! << std :: endl; }

I'm getting into C++11 threads and have run into a problem.

I want to declare a thread variable as global and start it later.

However all the examples I've seen seem to start the thread immediately for example

thread t(doSomething);

What I want is

thread t;

and start the thread later.

What I've tried is

if(!isThreadRunning) { thread t(readTable); }

but now t is block scope. So I want to declare t and then start the thread later so that t is accessible to other functions.

Thanks for any help.

解决方案

std::thread's default constructor instantiates a std::thread without starting or representing any actual thread.

std::thread t;

The assignment operator moves the state of a thread object, and sets the assigned-from thread object to its default-initialized state:

t = std::thread(/* new thread code goes here */);

This first constructs a temporary thread object representing a new thread, transfers the new thread representation into the existing thread object that has a default state, and sets the temporary thread object's state to the default state that does not represent any running thread. Then the temporary thread object is destroyed, doing nothing.

Here's an example:

#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; }

更多推荐

在C ++中延迟启动一个线程11

本文发布于:2023-10-18 15:14:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!