我试图编写一个线程,该线程将在我的主程序的后台运行并监视某事。在某个时候,主程序应该向线程发出信号以使其安全退出。这是一个最小示例,该示例以固定的时间间隔将本地时间写入命令行。
#include <cmath>
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
int func(bool & on)
{
while(on) {
auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << ctime(&t) << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
bool on = true;
std::future<int> fi = std::async(std::launch::async, func, on);
std::this_thread::sleep_for(std::chrono::seconds(5));
on = false;
return 0;
}
当未通过引用传递“on”变量时,此代码将编译并产生预期的结果,但线程永远不会终止。通过引用传递变量后,我会收到编译器错误
In file included from /opt/extlib/gcc/5.2.0/gcc/5.2.0/include/c++/5.2.0/thread:39:0,
from background_thread.cpp:3:
/opt/extlib/gcc/5.2.0/gcc/5.2.0/include/c++/5.2.0/functional: In instantiation of ‘struct std::_Bind_simple<int (*(bool))(bool&)>’:
/opt/extlib/gcc/5.2.0/gcc/5.2.0/include/c++/5.2.0/future:1709:67: required from ‘std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...) [with _Fn = int (&)(bool&); _Args = {bool&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = int]’
background_thread.cpp:20:64: required from here
/opt/extlib/gcc/5.2.0/gcc/5.2.0/include/c++/5.2.0/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<int (*(bool))(bool&)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/opt/extlib/gcc/5.2.0/gcc/5.2.0/include/c++/5.2.0/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<int (*(bool))(bool&)>’
_M_invoke(_Index_tuple<_Indices...>)
您是否愿意提出一种解决此代码的方法?
红利问题:出了什么问题,为什么它可以与std::ref一起使用,但不能与普通&
最佳答案
std::ref
是一个开始,但还不够。只有在另一个线程保护了某个变量的情况下,c++才能保证知道另一个线程对该变量的更改,
a)原子,或
b)内存围栏(互斥量,condition_variable等)
在允许main完成之前,同步线程也是明智的。请注意,我有一个对fi.get()
的调用,该调用将阻塞主线程,直到异步线程满足将来为止。
更新的代码:
#include <cmath>
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
#include <functional>
#include <atomic>
// provide a means of emitting to stdout without a race condition
std::mutex emit_mutex;
template<class...Ts> void emit(Ts&&...ts)
{
auto lock = std::unique_lock<std::mutex>(emit_mutex);
using expand = int[];
void(expand{
0,
((std::cout << ts), 0)...
});
}
// cross-thread communications are UB unless either:
// a. they are through an atomic
// b. there is a memory fence operation in both threads
// (e.g. condition_variable)
int func(std::atomic<bool>& on)
{
while(on) {
auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
emit(ctime(&t), "\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 6;
}
int main()
{
std::atomic<bool> on { true };
std::future<int> fi = std::async(std::launch::async, func, std::ref(on));
std::this_thread::sleep_for(std::chrono::seconds(5));
on = false;
emit("function returned ", fi.get(), "\n");
return 0;
}
示例输出:
Wed Jun 22 09:50:58 2016
Wed Jun 22 09:50:59 2016
Wed Jun 22 09:51:00 2016
Wed Jun 22 09:51:01 2016
Wed Jun 22 09:51:02 2016
function returned 6
根据要求,对
emit<>(...)
的解释template<class...Ts> void emit(Ts&&...ts)
emit
是一个返回void并通过x值引用(即const ref,ref或r-value ref)获取任意数量参数的函数。 IE。它会接受任何东西。这意味着我们可以致电:emit(foo())
-使用函数的返回值(r值)调用emit(x, y, foo(), bar(), "text")
-使用两个引用,2个r值引用和一个字符串文字using expand = int[];
将类型定义为不确定长度的整数数组。当实例化expand
类型的对象时,我们将仅使用它来强制表达式的求值。实际的数组本身将被优化器丢弃-我们只希望构造它的副作用。void(expand{ ... });
-强制编译器实例化数组,但是void cast告诉它我们永远不会使用实际的数组本身。((std::cout << ts), 0)...
-对于每个参数(以ts表示),在数组的构造中扩展一个术语。请记住,数组是整数。 cout << ts
将返回ostream&
,因此在简单地计算表达式0之前,我们使用逗号运算符对ostream<<
进行顺序排序。零实际上可以是任何整数。没关系这个整数在概念上存储在数组中(无论如何都将被丢弃)。0,
-数组的第一个元素为零。这适用于有人不带参数调用emit()
的情况。参数包Ts
将为空。如果我们没有这个前导零,则对数组的最终求值为int [] { }
,它是一个零长度的数组,在c++中是非法的。初学者的其他注意事项:
数组的初始化程序列表中的所有内容都是表达式。
表达式是导致某些对象的“算术”运算序列。该对象可以是实际对象(类实例),指针,引用或基本类型(如整数)。
因此,在这种情况下,
std::cout << x
是通过调用std::ostream::operator<<(std::cout, x)
(或其等效的自由函数,取决于x是什么)而计算出的表达式。该表达式的返回值始终为std::ostream&
。将表达式放在方括号中不会改变其含义。它只是强制订购。例如
a << b + c
的意思是“a左移(b加c)”,而(a << b) + c
的意思是“a左移b,然后加c”。逗号“,”也是运算符。
a(), b()
的意思是'调用函数a,然后丢弃结果,然后调用函数b。返回的值应为b'返回的值。因此,在进行一些精神体操时,您应该能够看到
((std::cout << x), 0)
的意思是“调用std::ostream::operator<<(std::cout, x)
,丢弃所得的ostream引用,然后评估值0”。该表达式的结果为0,但是将x传输到cout
的副作用将在我们得到0'之前发生。因此,当
Ts
是(例如)一个int和一个字符串指针时,Ts...
将是像这样的类型列表<int, const char*>
,而ts...
将实际上是<int(x), const char*("Hello world")>
因此,表达式将扩展为:
void(int[] {
0,
((std::cout << x), 0),
((std::cout << "Hello world"), 0),
});
在婴儿步骤中意味着:
当然,优化器会发现该数组从未使用过(因为我们没有给它命名),因此它删除了所有不必要的位(因为这就是优化器所做的事情),它等效于:
关于c++ - 线程: Termination of infinite loop thread in c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960797/