Click here to Skip to main content
15,925,255 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created thread by using std::thread in C++.
std::thread thread_variable(function_name);


With below command, it will create a thread and work byhimself.
And I need to terminate this thread by using thread_variable in another thread.

How can this be done?
Thank you

What I have tried:

I have tried to use desctructor of std::thread, but thread is working well.
Thank you
Posted
Updated 15-Feb-18 10:03am
v2

1 solution

Usually, worker threads are either blocked waiting for an event or they are spinning in a loop, updating and looking for other work to do. One easy way to do this to make a variable for each worker thread that indicates when it should terminate itself. If the thread objects are accessible to your "other" thread then it can set this variable to true for the thread that should terminate. I have done this kind of thing many times and it works well while being very easy to implement.
 
Share this answer
 
Comments
Member 13622714 15-Feb-18 18:44pm    
Could you please give me an example code what you used before?
(Exactly, I want to terminate thread immediately. I don't want to wait until thread is done completely.)

Thank you in advance.
Rick York 15-Feb-18 21:59pm    
No, I can't but it's usually along the lines of

if( m_Exit )
return; // or break;

That's it. The thread checks the flag and breaks out of its loop or returns from the function or method. The worker threads I use are always in wait loops so they just break from the loop and end themselves.

If your thread calls WaitForMultipleObjects then you could potentially create an event to signal exit, add it to the object array, and set the event when you want unblock the thread. There is lots of sample code around for all of those things.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900