How to terminate or stop an individual thread in C ++?

I am interested in stopping / stopping / killing a separate thread in C ++. How can I do that?

void myThread() { int loop = 0; while(true) { std::this_thread::sleep_for(std::chrono::seconds(5)); ++loop; } } void testThread() { std::thread globalThread(myThread); globalThread.detach(); } int main(void) { testThread(); for(unsigned int i=0; i < 1000; i++) { cout << "i = " << i << endl; } return 0; } 

The reason I would like to “stop” / “finish” globalThread () is because valgrind lists that it is a “possibly lost” type of memory leak (152 bytes). What is the best way to handle this?

+6
source share
4 answers

There are no provisions to stop another thread; regardless of whether he separated or joined.

The only way to stop the stream is to return the stream from the initial function of the stream.

In this particular case, I would suggest the following changes:

  • Do not disconnect the thread. Create it in main ().
  • Add value bool and std::mutex , bool gets initialized to false
  • Each time through the internal loop of the thread, block the mutex with std::unique_lock , take the value bool, then unlock the mutex. After unlocking the mutex, if bool was true , break out of the loop and return.
  • In main () before exiting: lock the mutex, set the bool flag to true , unlock the mutex, then attach the thread

This is not ideal, as the second thread checks the bool flag and returns it up to five seconds. But this will be the first tep.

+8
source

You can go below the C ++ standard and use OS-specific functions, such as sending your own signal process when setting the signal mask so that it is delivered only to a separate stream - the handler can set a flag polled from your stream, if your main procedure waits longer than the polling period plus a bit, you can guess that it should have stopped; -P. The same general idea can be used with any other signaling mechanism, such as the atom flag variable terminate-asap.

Alternatively, and only as a last resort, pthread_cancel and the like. Please note that asynchronous invalidation like this is a very dangerous thing in general - you have to be careful that the thread you terminate cannot be in any code with blocked / taken resources or you may have deadlocks and / and deadlocks or undefined behavior. For example, your code calls std::this_thread::sleep_for(std::chrono::seconds(5)); - what if it requests the OS to call back when the interval expires, but the function subsequently uses the completed stack stack to continue? An example where this can be safe is that a thread executing several prime numbers crunches in a loop inside your application.

Otherwise, Sam will answer alternative documents if you avoid disconnecting the thread in the first place ....

+1
source

It is not possible to completely disconnect a disconnected thread. This will require waiting for the cleanup to complete, and you can only do this if the stream is compatible.

Consider, for example, if a stream contains a mutex, which is required to create another stream for clean closure. The only way to clear this thread is to force it to release this mutex. This will require collaboration with the threads.

Consider if the stream opened the file and contains a lock on this file. Canceling a thread will lock the file until the process terminates.

Consider if a stream contains a mutex that protects some general state and temporarily puts this split state into an inconsistent state. If you terminate the stream, either the mutex will never be released, or the mutex will be released with protected data in an inconsistent state. This may cause a malfunction.

You need to work with threads to completely close it.

0
source

If this is Windows code (say, under MSVC), you can call the TerminateThread () function, and this will kill the thread, but first you need to check if the threads can be killed, if you want to leave corrupted / half-written data :)

Edit: In order to understand the essence and explain how this can be useful in the context of memory leaks, if a thread allocates a heap, then terminating the stream leaves the heap data loose, however, even if you use the heap for a thread, then you can have access to this heap from others threads / processes in the application and release it from outside the thread when you terminate it by calling the TerminateThread function. Or, alternatively, you can design the application so that the heap is supported by another thread, so that the dedicated thread only uses the stack and takes away access to the heap that already exists, then there is no possibility of memory leak in the dedicated thread, even if the thread is clearly killed. You can theoretically also get a heap lock under windows, although there are several ways you could get around this, for example, you could explicitly unlock this part of the heap after you end the stream using a low library system call and insert your own a lock around this area of ​​the heap so that other threads do not remove the lock while it is unlocking - i.e. A double lock that can be locked and unlocked by the parent process, but that any other threads expect to unlock before accessing this area of ​​the heap (if they use it at all). The great thing about threads is that they share a bunch, so there are many ways to solve this problem with or without thread destruction.

-1
source

Source: https://habr.com/ru/post/974784/


All Articles