简体   繁体   English

有没有一种创建线程的方法,但是可以使用C ++ 11延迟执行而不使用operator =

[英]Is there a way to create a thread but defer it's execution using C++11 without using the operator=

two threads are created if i use the following: 如果我使用以下创建两个线程:

void func()
{}

std::thread td1;//thread  object created.
...
...
//defer the running of td1 until now
td1 = std::thread(func);//temp thread object(rvalue) created

Is there a way to achieve the defer execution but without creating two threads? 有没有一种方法可以实现延迟执行而不创建两个线程?

I'm not sure what the point is, but... 我不确定这是什么意思,但是...

No operator= , though two threads are constructed: 没有operator= ,尽管构造了两个线程:

std::thread td1;
...
std::thread(func).swap(td1);

Or no operator= and only one thread constructed: 或不使用operator= ,仅构造一个线程:

std::promise<void> p;
std::thread td1([&]() {
   p.get_future().wait();
   func();
});
...
p.set_value();

td1.join(); // Can't let p go out of scope pending the thread.

Maybe what you really want is: 也许您真正想要的是:

std::unique_ptr<std::thread> td1;
...
td1.reset(new std::thread(func));
std::thread td1;

That creates a thread object, but it does not create a thread. 这将创建线程对象,但不会创建线程。 So: 所以:

std::thread td1;
td1 = std::thread(func);

is perfectly fine code even if you are concerned about performance. 即使您担心性能,它也是完美的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM