Click here to Skip to main content
15,995,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have created thread by using std::thread in C++.

std::thread thread_variable(function_name);


With above code, it will create a thread.
And I need to terminate this thread by using thread_variable in another thread, like TerminateThread() win32 api.

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 16-Feb-18 1:53am
Comments
Afzaal Ahmad Zeeshan 16-Feb-18 5:29am    
To communicate a command from one thread to another, you would need to "signal" the thread and then perform an action. In most simple of the ways, that can be done using a variable that notifies ThreadXYZ to finish. A thread will execute just once. In this scenario, most likely the thread is in a while loop that is preventing the thread to finish.

A thread finishes itself; based on a condition, or the statements. To terminate a thread, you can kill it, but that is not a recommended approach it is might lead to memory leaks.

Don't post again and again the same question. There is no way in standard C++ to do what you want. Rick York posted here[^] the usual way to accomplish the task.
An alternative is using the underlying API of your operative system by means of the thread native_handle.

See, for instance c++ - How to stop an std::thread from running, without terminating the program - Stack Overflow[^].
 
Share this answer
 
There are different solutions possible, the most obvious is to use a global variable (boolean, mutex or handle) to signal the exit.

pseudo-code:

C++
bool stopThread = false;

void threadOne()
{
  if( timeToLeave ) {
    stopThread = true;
  }
}

void threadTwo()
{
  while( !stopThread ) {
    //do silly stuff, maybe some waiting
  }
}
If you dont like it read the documenation and "maybe" you can do stuff like that
C++
std::thread *myThread = new std::thread(...);//some working constructor
delete myThread;
I wish you good luck...
 
Share this answer
 
Comments
OmidXavaX 16-Sep-18 11:33am    
this code not work on release , it's an pedagogic demonstration

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