Terminate thread without memory leak

Hello everyone,

I want to implement the following logic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int global_count;

// this should not be changed, like its name, its a black box
void blackbox() {
    while (true) {
        printf(".");
        global_count+=1;
    }
}

int main()
{
    int THREAD_NUM = 5;

    for (int i=0; i<THREAD_NUM; i++) {

        std::thread t(blackbox);
        t.join();  // make thread t ONLY run for 5 seconds

    }
    return 0;
}


I know that ppl will say terminating a thread without return is dangerous and shouldn't be done. I also noticed there is a clean way, which is to use a condition variable and check it constantly, but this will need modification in the "blackbox()" - which can not be done in my case.

Is there any other workaround for such a problem? Can I call std::terminate() or std::abort() to stop the thread without memory leak?


Many thanks,
chuuuing
> Is there any other workaround for such a problem?
No.
C++20 has a class jthread which can be cancelled. This might be more what you need.
Shouldn't global_count be atomic?

Whether std::terminate() has an adverse effect depends upon what resources the thread has acquired during its execution.

For the given example, std::terminate could be used.
thanks for the reply. The program I'm working on is written in C++ 11 and I'm just modifying it for a new feature. So I might not be able to use jthread? but it's interesting to know.
If it is not restricted to thread, can I for example use process?
> If it is not restricted to thread, can I for example use process?
Instead of fumbling around in the dark, how about you tell us what the problem is, not your "solution" guesses.
https://xyproblem.info/
Yes, you could start a process and then kill it after 5 seconds. More expensive than using a thread.

Might be better for the thread to decide itself when it's going to stop; perhaps pass in the timeout through a parameter.
Last edited on
if you fear to just kill it, can you suspend it?
Line 18 waits for t to complete. So your code starts a thread, waits for it to finish, then moves on to start the next thread.

I don't see a method in the <thread> to kill a specific thread, so the individual threads must stop themselves.
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
27
28
#include <thread>
#include <iostream>
#include <vector>

using namespace std;

int global_count;

void blackbox()
{
    time_t endTime = time(0)+5;
    while (time(0) < endTime) {
	cout << this_thread::get_id() << ' ';
	++global_count;
    }
}

int main(void) {
    vector<thread> threads;

    for (unsigned i=0; i<5; ++i) {
	threads.emplace_back(blackbox);
    }

    for (unsigned i=0; i<5; ++i) {
	threads[i].join();
    }
}

Last edited on
Topic archived. No new replies allowed.