简体   繁体   English

是否有可能在C ++中用另一个线程终止线程?

[英]is it possible to terminate a thread with another thread in c++?

I want to write a program in which many functions run simultaneously. 我想编写一个程序,其中许多功能可以同时运行。 I already figured out that in order to do that I need to use threads. 我已经弄清楚了,为了做到这一点,我需要使用线程。 In my program a routine of heating and rotating an object with different temperatures and velocities has to run for a determined period of time in a loop. 在我的程序中,以不同的温度和速度加热和旋转物体的例程必须循环运行一段确定的时间。 Once the time has passed I want the process to continue with my next heating/rotating (...). 时间过去后,我希望该过程继续进行下一个加热/旋转(...)。 My idea was to write a "timer thread" that is able to end the current routine in some way, and skip to the next one. 我的想法是编写一个“计时器线程”,它可以某种方式结束当前例程,然后跳到下一个例程。 Is this possible? 这可能吗?

I suppose most ways to do this are going to involve a shared flag between the working thread and the thread that signals it to stop working. 我想大多数方法都将在工作线程和发出停止工作信号的线程之间包含一个共享标志。

So you might have something along these lines: 因此,您可能会遵循以下原则:

// Use a std::atomic_bool to signal the thread safely
void process_stuff(std::atomic_bool& stop_processing)
{
    while(!stop_processing) // do we keep going?
    {
        // do some measurements or action

        std::this_thread::sleep_for(std::chrono::milliseconds(1)); // wait for next action
    }
}

Elsewhere in another thread ... 在另一个线程的其他地方...

std::atomic_bool stop_processing{false};

// start thread (use std::ref() to pass by reference)
std::thread proc_thread(process_stuff, std::ref(stop_processing));

// wait for some time...
std::this_thread::sleep_for(std::chrono::seconds(3));

stop_processing = true; // signal end
proc_thread.join(); // wait for end to happen

// now create a new thread...

In the initiating thread, by changing the value of the variable stop_processing you signal the running thread to stop looping, in which case it ends gracefully. 在启动线程中,通过更改变量stop_processing的值,您可以向运行中的线程发出停止循环的信号,在这种情况下,该循环会正常结束。

Check this: 检查一下:

int main() {
    // first thread
    auto thread1 = std::make_unique<std::thread>([]() {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "over\n";
    });

    // disposing to second thread
    std::thread([thread2 = std::move(thread1)](){
        thread2->join();
    }).detach();

    //spinning a new thread
    thread1.reset(new std::thread([]() {
       std::this_thread::sleep_for(std::chrono::seconds(1));
       std::cout << "next over\n";
    }));
   thread1->join();  

   return 0;
}

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

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