在C ++中,如何重用已完成执行的标准线程? [英] In C++, how can I reuse a standard thread that has finished execution?

查看:150
本文介绍了在C ++中,如何重用已完成执行的标准线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的C ++方法的 main()方法中有这行代码:

I have this line of code in my main() method of my C++ method:

std::thread foo (bar);

这很好。但是,我想在任何时候运行这个相同的线程,我想基于外部输入。如何重新使用此线程来再次运行线程?

That works fine. However, I would like to run this same thread any time that I want to based on external input. How can I re-use this thread to run the thread again?

我这样做的原因是我有两个函数需要同时运行:阻塞并接收输入x的输出,并以设定的间隔将数据输出到输出。另一个是阻塞并基于外部输入产生输出y。这基本上是它应该看起来像:

The reason I'm doing this is I have two functions that need to be ran at the same time: one that is blocking and takes an input, x, and outputs the data to the output at set intervals. The other one is blocking and produces an output, y, based on external input. This is basically what it should look like:

int shared_x = 0;
int producer_x = 0;
int consumer_x = 0;

std::thread producer (foo);    //Modifies foo_x
std::thread consumer (bar);    //Outputs based on foo2_x
while( ;; ) {
    if(producer .join()) {
        shared_x = producer_x;
        //How should I restart the thread here?
    }
    if(consumer.join()) {
        consumer_x = shared_x;
        //Here too?
    }
}

似乎处理整个线程安全问题允许他们在几乎没有时间等待的同时安全操作。唯一的问题是我不知道如何重新启动线程。

That seems to handle the whole thread safety issue and allow them both to safely operate at the same time with little time waiting. The only issue is I don't know how to restart the thread. How do I do this?

推荐答案

通过阅读一些文档,我发现这是有效的:

Reading through some documentation, I found this works:

myOldThread = thread(foobar);

它似乎只是覆盖旧线程,创建一个全新的功能。我不知道ID是否改变,如果第一个线程没有执行,会发生什么,但这将是一个有趣的实验,看看什么变化。

All it seems to do is it overwrites the old thread and creates the equivalent of a brand new function. I don't know if the ID changes or what would happen if the first thread hadn't finished executing, but that would be an interesting experiment to see what changes.

(边注:使用PThreads因为GCC支持Debian线程是坏的。)

(Side note: using PThreads since GCC support for threads on Debian is bad.)

这篇关于在C ++中,如何重用已完成执行的标准线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆