join equivalent in Windows - c++

How do I wait for a thread to die in Windows? This is what I want my code to look like:
main thread:
creating thread: thread1
waiting for thread1 to die
//rest of the code
I am using Win32 API.

It's easy: the WaitForSingleObject can block current thread given the other thread's handle.
void Thread1Proc()
{
HANDLE hThread2 = CreateThread(...);
WaitForSingleObject(hThread2, INFINITE);
// by now thread #2 is over
}

Related

pthread mutex lock - Does it check periodically or OS wakes it up [duplicate]

This question already has answers here:
How pthread_mutex_lock is implemented
(3 answers)
Closed 4 years ago.
If Thread1 tried to lock resource locked by Thread2.
Does it go to sleep for finite time ?
Now if the Thread2 unlock the mutex then how would Thread1 will come to know that resource is available ? Is the operating system wakes it up or it checks for resource periodically ?
your second assumption is correct. When a mutex is locked by a thread already, all the remaining threads that are trying to lock it again will be placed on hold and will be in the sleep state. Once the mutex lock is unlocked the O/S wakes them all up and who can unlock first can access the lock. This is not in FIFO basis, actually there is no rule which thread should get first preference to lock the mutex once wakes up. You can consider my below example where I have use condition variable to control the threads:-
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock3 = PTHREAD_MUTEX_INITIALIZER;
int TRUE = 1;
void print(char *p)
{
printf("%s",p);
}
void * threadMethod1(void *arg)
{
printf("In thread1\n");
do{
pthread_mutex_lock(&lock1);
pthread_cond_wait(&cond1, &lock1);
print("I am thread 1st\n");
pthread_cond_signal(&cond3);/* Now allow 3rd thread to process */
pthread_mutex_unlock(&lock1);
}while(TRUE);
pthread_exit(NULL);
}
void * threadMethod2(void *arg)
{
printf("In thread2\n");
do
{
pthread_mutex_lock(&lock2);
pthread_cond_wait(&cond2, &lock2);
print("I am thread 2nd\n");
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&lock2);
}while(TRUE);
pthread_exit(NULL);
}
void * threadMethod3(void *arg)
{
printf("In thread3\n");
do
{
pthread_mutex_lock(&lock3);
pthread_cond_wait(&cond3, &lock3);
print("I am thread 3rd\n");
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&lock3);
}while(TRUE);
pthread_exit(NULL);
}
int main(void)
{
pthread_t tid1, tid2, tid3;
int i = 0;
printf("Before creating the threads\n");
if( pthread_create(&tid1, NULL, threadMethod1, NULL) != 0 )
printf("Failed to create thread1\n");
if( pthread_create(&tid2, NULL, threadMethod2, NULL) != 0 )
printf("Failed to create thread2\n");
if( pthread_create(&tid3, NULL, threadMethod3, NULL) != 0 )
printf("Failed to create thread3\n");
pthread_cond_signal(&cond1);/* Now allow first thread to process first */
sleep(1);
TRUE = 0;/* Stop all the thread */
sleep(3);
/* this is how we join thread before exit from a system */
/*
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);*/
exit(0);
}
Here I am using 3 mutexs and 3 conditions. With the above example you can schedule/control or prioritize any number of threads in C. If you see the first thread here it locked mutex lock1 and waiting on cond1, likewise second thread locked mutex lock2 and waits on condition cond2 and 3rd thread locked mutex lock3 and waits on condition cond3. This is the current situation of all the threads after they are being created and now all the threads are waiting for a signal to execute further on its condition variable. In the main thread (i.e. main function, every program has one main thread, in C/C++ this main thread created automatically by operating system once control pass to the main method by kernal) we are calling pthread_cond_signal(&cond1); once this system call done thread1 who was waiting on cond1 will be release and it will start executing. Once it finished with its task it will call pthread_cond_signal(&cond3); now thread who was waiting on condition cond3 i.e. thread3 will be release and it will start execute and will call pthread_cond_signal(&cond2); which will release the thread who is waiting on condition cond2 i.e. in this case thread2.
Fundamental information about the mutex (MUtual Exclusion locks)
A mutex is a special lock that only one thread may lock at a time. If a thread locks a mutex and then a second thread also tries to lock the same mutex, the second thread is blocked, or put on hold. Only when the first thread unlocks the mutex is the second thread unblocked—allowed to resume execution.
Linux guarantees that race conditions do not occur among threads attempting to lock a mutex; only one thread will ever get the lock, and all other threads will be blocked.
A thread may attempt to lock a mutex by calling pthread_mutex_lock on it. If the mutex was unlocked, it becomes locked and the function returns immediately.
What happens trying to lock the when its locked by another thread?
If the mutex was locked by another thread, pthread_mutex_lock blocks execution and returns only eventually when the mutex is unlocked by the other thread.

Kill an std::thread that wasn't joined

So I have a thread that I was running using .join() but I needed an interactive user interface while running the thread so I stopped using join because it halted the program while it ran. The ui has a stop button to kill the thread and now I need a way to stop the thread without killing the whole program because I can't use .detach(). Thanks!
There is no safe way to unilaterally terminate a thread. Instead, the thread's code must periodically check whether the GUI thread has requested that it exit.
I'm not familiar with the new C++ library functions, but I believe you can do this with atomic_bool, e.g., see this question.
you could pass a reference to a bool variable to the thread and check if it is true. if it is, return from the thread.
Example:
bool terminate = false;
std::mutex m;
std::thread t([&terminate,&m] {
std::unique_lock<std::mutex> lm{m,std::defer_lock}; //don't lock yet
int i = 0;
while (true) {
lm.lock(); //protect terminate -> no race conditions
if (terminate)
return;
lm.unlock(); //release lock for terminate
//do what your thread should do
std::cout << i++ << std::endl;
}
});
/*
do something else here
*/
m.lock();
terminate = true;
m.unlock();
t.join();

How to keep a process running?

I have a process that starts several threads which do some stuff, listen to some ports, etc.
After it starts all threads, the main thread currently goes into an infinite loop:
It's something like:
int main()
{
//start threads
while (true)
{
sleep(1000);
}
}
The extra sleep assures the main thread doesn't eat the processor.
Is this approach ok? Is there an industry standard on how a process is kept alivet? Thanks.
EDIT: Some clarifications:
the threads are listeners, so a join or WaitForSingleObject isn't an option. Usually I could use join here, but the threads are started by a third client library and I don't have any control over them.
doing some processing in the main thread doesn't make sense from a design point of view.
. Taken partially from the Linux Daemon Writing HOWTO, I assume you want something like this:
int main() {
pid_t pid;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
// now start threads & do the work
for( thread *t : threads ) {
join( t );
}
return 0;
}
This way the main process will exit, child process will spawn threads which will do the work. In the end the child process will wait for those threads to finish before exiting itself.
I'd suggest you to have your main thread waiting for the termination of the others:
int main( ) {
// start threads
for( thread *t : threads ) {
join( t );
}
// finalize everything or restart the thread
return 0;
}
If you're using POSIX threads, the pthread_join function will do this.
I don't believe that there is an industry standard.
What you have is a perfectly acceptable way of running the main thread. However you may want to include a way to break out of the loop.
Other methods include:
Waiting for all the worker threads to complete using a join command.
Waiting on an event in the the main thread which can be signalled to exit the loop.
Using the main thread to do some of the processing currently done by a worker thread.
Periodically checking a boolean flag to decide whether to exit or not.
At the end of the day, it depends on your specific requirements.

Know if a pthread thread is Alive in a safe way

I made a multithread application that generates/destroy 100 threads continuously:
//Here is the thread class (one by every thread
struct s_control
{
data_in[D_BUFFER_SIZE];//data in to thread
data_out[D_BUFFER_SIZE];//data generated by the thread
//I use volatile in order to status data is avaiable in and out of the thread:
volatile __int16 status;//thread state 0=empty,1=full,2=filling (thread running)
}*control;
//Here is the thread main function
static void* F_pull(void* vv)//=pull_one_curl()
{
s_control* cc = (s_control* ) vv;
//use of cc->data_in and filling of cc->data out
cc->status=1; //Here advises that thread is finished and data out is filled
return NULL;
}
void main()
{
initialization();
control=new s_control[D_TAREAS];
pthread_t *tid=new pthread_t[D_TAREAS];
for (th=0;th<D_TAREAS;th++)
{ //Access to status of thread at the beginning
//(to avoid if it changes in the middle):
long status1=control[th].status
if (status1==0) //Thread finished and data_out of thread is empty
{ control[i2].status=2; //Filling in (thread initiated)status LLENANDO
error = pthread_create(&tid[th],NULL,F_pull,(void *) &control[th]);
}
else if (status1==1) //Thread finished and data_out of thread is full
{
//do things with control[th].data_out;
//and fill in control[th].data_in with data to pass to next thread
control[th].status=0; //Thread is finished and now its data_out is empty
}
else
{
//printf("\nThread#%li:filling",i2);
}
}while(!_kbhit());
finish();
}
Then as you can see, at the end of the thread, I used the variable volatile to advise that thread is about to exit:
begin of thread{ ....
cc->status=1; //Here advises that thread is finished and data out is filled
return NULL;
}//END OF THREAD
But after cc->status is set to 1 thread is not finished yet (it exist one more line)
So I do not like set status inside the thread.
I tried pthread_kill, but it didn´t work, because it does not work until thread is alive, as can be seen at:
pthread_kill
I am not sure if this answers your question, but you can use pthread_join() to wait for a thread to terminate. In conjunction with some (properly synchronized) status variables, you should be able to achieve what you need.

How to kill a MFC Thread?

I spawn a thread using AfxBeginThread which is just an infinite while loop:
UINT CMyClass::ThreadProc( LPVOID param )
{
while (TRUE)
{
// do stuff
}
return 1;
}
How do I kill off this thread in my class destructor?
I think something like
UINT CMyClass::ThreadProc( LPVOID param )
{
while (m_bKillThread)
{
// do stuff
}
return 1;
}
and then set m_bKillThread to FALSE in the destructor. But I still need to wait in the destructor until the thread is dead.
Actively killing the thread:
Use the return value of AfxBeginThread (CWinThread*) to get the thread handle (m_hThread) then pass that handle to the TerminateThread Win32 API. This is not a safe way to terminate threads though, so please read on.
Waiting for the thread to finish:
Use the return value of AfxBeginThread (CWinThread*) to get the member m_hThread, then use WaitForSingleObject(p->m_hThread, INFINITE); If this function returns WAIT_OBJECT_0, then the thread is finished. Instead of INFINITE you could also put the number of milliseconds to wait before a timeout happens. In this case WAIT_TIMEOUT will be returned.
Signaling to your thread that it should end:
Before doing the WaitForSingleObject just set some kind of flag that the thread should exit. Then in your main loop of the thread you would check for that bool value and break the infinite loop. In your destructor you would set this flag then do a WaitForSingleObject.
Even better ways:
If you need even more control you can use something like boost conditions.
BTW, About TerminateThread(), use it this way.
DWORD exit_code= NULL;
if (thread != NULL)
{
GetExitCodeThread(thread->m_hThread, &exit_code);
if(exit_code == STILL_ACTIVE)
{
::TerminateThread(thread->m_hThread, 0);
CloseHandle(thread->m_hThread);
}
thread->m_hThread = NULL;
thread = NULL;
}
First you have to start the thread in a way so MFC doesn't delete the thread object when it's finished, the default setting for MFC thread is to delete itself so you want to turn that off.
m_thread = AfxBeginThread(ThreadProc, this, THREAD_PRIORITY_NORMAL ,CREATE_SUSPENDED);
m_thread->m_bAutoDelete = FALSE;
m_thread->ResumeThread();
Now in the thread, you want a mechanism that the caller thread can send it a signal to end itself. There are multiple ways, one is the WaitForSingleObject to check the status of the signal or another way is to simply send this thread a message to end itself. This is graceful ending rather killing it.
While this thread is ending itself (= exiting the thread function, cleaning up), you can have the main thread wait on it to finish before it exits.
int wait = 2000 // seconds ( I am waiting for 2 seconds for worker to finish)
int dwRes = WaitForSingleObject( m_thread->m_hThread, wait);
switch (dwRes)
{
case WAIT_OBJECT_0:
TRACE( _T("worker thread just finished") ); break;
case WAIT_TIMEOUT:
TRACE( _T("timed out, worker thread is still busy") ); break;
}
Note setting m_bAutoDelete = FALSE above made it possible we still have a valid handle when thread finishes so we can wait on it. The last thing you want to do now is delete the CWinThread object to free its memory (since we took the responsibility to do that).
You must wait, until thread do all stuff.
if(WaitForSingleObject(thread_handle, INFINITE) == WAIT_OBJECT_0)
;//all right
else
;//report error
beware using TerminateThread function, this is very dangerous.