jjzjj

c++ - 线程: Termination of infinite loop thread in c++

coder 2024-02-09 原文

我试图编写一个线程,该线程将在我的主程序的后台运行并监视某事。在某个时候,主程序应该向线程发出信号以使其安全退出。这是一个最小示例,该示例以固定的时间间隔将本地时间写入命令行。

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

    在婴儿步骤中意味着:
  • 分配长度为3的数组
  • 数组[0] = 0
  • 调用std::cout < x,丢弃结果,array="" [1]="0">
  • 调用std::cout <“hello world”,丢弃结果,array="" [2]="0">

  • 当然,优化器会发现该数组从未使用过(因为我们没有给它命名),因此它删除了所有不必要的位(因为这就是优化器所做的事情),它等效于:
  • 调用std::cout <>
  • 调用std::cout <“hello>
  • 关于c++ - 线程: Termination of infinite loop thread in c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960797/

    有关c++ - 线程: Termination of infinite loop thread in c++的更多相关文章

    1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

      我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

    2. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

      我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

    3. ruby - 使用 `+=` 和 `send` 方法 - 2

      如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

    4. ruby - 如何让Ruby捕获线程中的语法错误 - 2

      我正在尝试使用ruby​​编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?

    5. ruby - 如何在 ruby​​ 中运行后台线程? - 2

      我是ruby​​的新手,我认为重新构建一个我用C#编写的简单聊天程序是个好主意。我正在使用Ruby2.0.0MRI(Matz的Ruby实现)。问题是我想在服务器运行时为简单的服务器命令提供I/O。这是从示例中获取的服务器。我添加了使用gets()获取输入的命令方法。我希望此方法在后台作为线程运行,但该线程正在阻塞另一个线程。require'socket'#Getsocketsfromstdlibserver=TCPServer.open(2000)#Sockettolistenonport2000defcommandsx=1whilex==1exitProgram=gets.chomp

    6. ruby - 如何计算 Liquid 中的变量 +1 - 2

      我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

    7. ruby - Rails 开发服务器、PDFKit 和多线程 - 2

      我有一个使用PDFKit呈现网页的pdf版本的Rails应用程序。我使用Thin作为开发服务器。问题是当我处于开发模式时。当我使用“bundleexecrailss”启动我的服务器并尝试呈现任何PDF时,整个过程会陷入僵局,因为当您呈现PDF时,会向服务器请求一些额外的资源,如图像和css,看起来只有一个线程.如何配置Rails开发服务器以运行多个工作线程?非常感谢。 最佳答案 我找到的最简单的解决方案是unicorn.geminstallunicorn创建一个unicorn.conf:worker_processes3然后使用它:

    8. arrays - Ruby 数组 += vs 推送 - 2

      我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

    9. += 的 Ruby 方法 - 2

      有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

    10. ruby - Ruby 1.9.1 中的 native 线程,对我有什么好处? - 2

      所以,Ruby1.9.1现在是declaredstable.Rails应该与它一起工作,并且正在慢慢地将gem移植到它。它具有native线程和全局解释器锁(GIL)。自从GIL到位后,原生线程是否比1.9.1中的绿色线程有任何优势? 最佳答案 1.9中的线程是原生的,但它们被“放慢了速度”,一次只允许一个线程运行。这是因为如果线程真的并行运行,它会混淆现有代码。优点:IO现在在线程中是异步的。如果一个线程阻塞在IO上,那么另一个线程将继续执行直到IO完成。C扩展可以使用真正的线程。缺点:任何非线程安全的C扩展都可能存在使用Thre

    随机推荐