End threads after 30 seconds execution

Hello everyone,

I want to stop the execution of some complex function after it runs for 30 seconds. I find some references saying I should use thread, but ppl also mention a thread shouldn't be terminated in any cases.

This is what I want to solve:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// condition_variable example
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock

std::mutex mtx;
std::condition_variable cv;

void complexFunction (int id) {
    std::unique_lock<std::mutex> lck(mtx);
    std::cout << "thread " << id << '\n';
    // this function may take hours
}

int main ()
{
    std::thread threads[10];
    for (int i=0; i<10; ++i)
    {
        threads[i] = std::thread(complexFunction,i);
        // TODO: stop the threads after 30 seconds
        continue;
    }

    return 0;
}


any idea how to do this?

Thanks!
Manage cancellations in the thread.
https://man7.org/linux/man-pages/man3/pthread_setcancelstate.3.html
https://man7.org/linux/man-pages/man3/pthread_cleanup_push.3.html

Thread checking for cancellation, if it doesn't call any functions marked as cancellation points.
https://man7.org/linux/man-pages/man3/pthread_testcancel.3.html

Controller telling the thread to die.
https://man7.org/linux/man-pages/man3/pthread_cancel.3.html
If the function may take hours but must be cancelled after some time, and modifying it is not an option, a safe alternative is to move it to a different process and killing the process after the specified time has elapsed without any results.
thanks for your reply!

I found out c++ doesn't provide a standard process library. which one would you recommend?
What OS?
MacOS
fork() is probably the easiest way to do it.
https://man7.org/linux/man-pages/man2/fork.2.html
Topic archived. No new replies allowed.