正在初始化可移动类的ctor中的std::thread
Initializing std::thread in ctor of movable class
我需要在类的ctor中初始化一个std::线程。线程应该运行类本身的成员函数。在ctor中,当尝试初始化线程时,程序会尝试运行成员函数。(实现了Move语义)。
Page::Page(Motion *_parent):
parent(_parent)
{
std::thread x(&Page::play,this);
starter = std::move(x);
}
程序运行this
的play()
!
编辑:我这样做:
void Page::start()
{
std::thread x(&Page::play,this);
x.join();
}
效果很好,但不知道是否可以。。。现在我正在使用std::bind
,如果这是标准的操作方式,我将替换代码。
std::thread
的构造函数会立即自动启动线程,然后新线程会调用所提供的函数,因此
std::thread x(&Page::play,this);
在新线程上自动调用CCD_ 5。
这与某些线程库(如.Net)不同,在某些线程库中,必须通过调用Start()
成员函数来显式启动线程。std::thread
不存在"延迟启动"功能。
如果在调用其他函数之前不希望线程真正启动,请不要在构造函数中初始化std::thread
对象,而是在start()
函数中初始化,如图所示。
如果在线程对象上调用join()
,那么代码将等待线程在调用join()
时完成。因此,如果像在示例start()
函数中那样,在构造线程对象之后立即放置联接,那么您还不如直接调用play()
,因为start()
在线程完成之前不会返回。
您不需要std::bind
和std::thread
——线程构造函数会自动处理绑定。
这样的东西怎么样:
#include <iostream>
#include <thread>
#include <functional>
struct Foo
{
Foo()
: thread(std::bind(Foo::bar, this))
{ }
~Foo()
{ thread.join(); }
static void bar(Foo *foo)
{ }
std::thread thread;
};
int main()
{
Foo foo;
}
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 理解GCC中的std::pow实现
- 捕获lambda中的std::数组
- 用C++中的std::condition_variable将线程置于死锁中会有风险吗
- 标准::unordered_map 中的 std::array 的值初始化
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- C++ IDE 不会推断/自动完成对模板类中的 std::array 下标表达式的成员访问
- 如何处理给定代码中的 std::out_of_range 错误?
- 为什么目录中的 std::filesystem::file_size 留给实现?
- C++ - 向量中的 std::unique_ptr <> 为 nullptr
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 访问基于范围的循环(如for_each)中的std::map迭代器
- 意外的模板与VC++中的std::void_t匹配
- 为什么一个表达式中的 std::string 连接给出的结果与逐个字符不同的结果?
- 如何识别容器中的 std::function 并将其删除?
- 列表中的 std::min_element 不返回最小值
- 将组合框信号连接到 Qt 中的 std::function 时出现问题