简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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