线程和右值引用
std::thread and rvalue reference
我想有某种委托类。我的方法的缩短版本如下,它的主要功能是启动新线程做一些事情(在这个例子中,它每秒打印文本):
void Flusher::start(){
m_continue.store(true);
m_thread = std::thread([](std::atomic<bool>& shouldContinue){
while(shouldContinue.load()){
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "sec passed" << std::endl;
}}, std::ref<std::atomic<bool>>(m_continue)
);
}
我担心的是,std::thread构造函数有以下签名:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
所以它接受右值reference作为第一个和第二个实参。如果是这样,那么我不应该在将shouldContinue
传递给std::thread
构造函数后使用它,因为它被移动了。
当然我想控制这个函数,因此我想在调用线程中使用shouldContinue来停止被调用的函数。很明显,我不想让这个变量成为全局变量。
我认为,std::ref
使一些魔术在那里,但我仍然不确定它是如何工作的(我看到std::ref
在创建新线程时的一些例子)。
我试图不关心的事实,这是右值引用,我使用shouldContinue
之后,没有崩溃,但我担心这是简单的未定义的行为。有人能告诉如果上面的代码是正确的,如果不是,如何做到这一点正确吗?
当&&与模板一起使用。
看看这个很好的解释:
http://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c/template <class T>
void func(T&& t) {
}
"时,,出现在类型推断上下文中,T&&获得特殊的意义。当func实例化时,T取决于传递给func的参数是左值还是右值。如果它是类型为U的左值,则T推导为U&如果是右值,则T被演绎为U:"
func(4); // 4 is an rvalue: T deduced to int
double d = 3.14;
func(d); // d is an lvalue; T deduced to double&
float f() {...}
func(f()); // f() is an rvalue; T deduced to float
int bar(int i) {
func(i); // i is an lvalue; T deduced to int&
}
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- condition_variable、引用和线程:谁拥有锁?
- 启动类函数作为失去引用的线程
- 将常量引用传递给线程
- 线程安全的引用计数队列C++
- 具有对象的右值引用的线程
- C++11 多线程,通过引用传递
- C++ 线程函数通过引用传递
- C 11线程汇编错误传递字符串作为复制的引用
- C++ 11 您可以通过不同线程中的引用安全地传递和访问 std::atomics 吗?
- 通过引用将变量传递给多个线程会损坏堆
- 线程函数中的通用引用
- 通过引用和多线程传递对象
- 如何在类中进行 c++ 多线程处理(将线程引用保留为成员 var)
- 为线程构造函数传递引用以将其绑定到函数失败
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 对抽象类的引用不能传递给线程函数?
- std::线程传递向量元素(按引用)
- 取消引用指向不同线程中的原子对象的只读非原子指针是否安全
- 引用计数类和多线程