What is a "wait thread"? - multithreading

The documentation for the RegisterWaitForSingleObject() function mentions a "wait thread", but I cannot find any explanation/reference on what that is exactly.
I presume it is not a regular thread, as otherwise RegisterWaitForSingleObject() would block a thread only waiting and doing nothing.

You pass a waitable object handle to RegisterWaitForSingleObject(), along with a timeout and a callback. It obtains a thread from an internal thread pool, and that thread waits on the object to be signaled or the timeout to elapse, and then it calls the callback. So, a "wait thread" is simply a thread that waits on something to happen.

Related

What happens if you await in a thread that isn't in the thread pool?

If I create a new thread like this:
Thread thread = new Thread(.....);
thread.Start(......);
What happens if a method inside that thread uses the await operator?
I understand that in a normal scenario this would cause .Net to save the state of the current execution and give the thread back to the thread pool so it can work on something else while we wait for the awaited method to complete, but what if this is not in a thread pool thread to begin with?
I understand that in a normal scenario this would cause .Net to save the state of the current execution and give the thread back to the thread pool so it can work on something else while we wait for the awaited method to complete, but what if this is not in a thread pool thread to begin with?
To clarify a bit, await will save the local state and then return. It doesn't give up the thread right away.
So, in this case, if the Thread's main method returns, then that thread exits. It isn't returned to the thread pool since it's not a thread pool thread; it just exits because its thread proc returned.
There are other scenarios, too:
If the thread is a UI thread, then it returns to its message loop. The thread keeps running, processing other messages.
If the thread is the main thread of a Console application, then it exits, which causes the Console app to exit.
What happens if a method inside that thread uses the await operator?
The same as any other time await is used:
await captures the "context" (SynchronizationContext.Current or TaskScheduler.Current). In this case, the context would be the thread pool context.
When the method is ready to resume, it resumes on that context.
So in this case, the await will return, causing the thread to exit. Then later, the rest of the method will run on a thread pool thread.
If you "create" the thread, you "manage" it.
Once the code scheduled to run on that thread finishes, the thread will be destroyed.
If you're running async/await code on a thread you crated, chances are that you will run out of that thread soon and pay the price of creating and destroying the thread for no benefit.
Thread pools are used to schedule short lived code and, with async/await that is the norm.
If you have some long running code that blocks, then it might be better to create your own thread.

What happens to a thread calling pthread_cond_signal?

When a thread calls pthread_cond_signal, one of the threads waiting on the condition will resume its execution. But what happens to the calling thread? Does it waits for the called thread to release the mutex and then it resumes?
For example, the waiting thread:
pthread_mutex_lock(&mut);
// ...
pthread_cond_wait(&cond, &mut);
// ...
pthread_mutex_unlock(&mut);
And the signaling thread:
pthread_mutex_lock(&mut);
// ...
pthread_cond_signal(&cond);
// ... has work to finish
pthread_mutex_unlock(&mut);
In this case, how can the signaling thread continue its work if the waiting thread has taken over the mutex?
The thread that calls pthread_cond_signal returns immediately. It does not wait for the woken thread (if there is one) to do anything.
If you call pthread_cond_signal while holding the mutex that the blocked thread is using with pthread_cond_wait, then the blocked thread will potentially wake from the condition variable wait, then immediately block waiting for the mutex to be acquired, since the signalling thread still holds the lock.
For the best performance, you should unlock the mutex prior to calling pthread_cond_signal.
Also, pthread_cond_wait may return even though no thread has signalled the condition variable. This is called a "spurious wake". You typically need to use pthread_cond_wait in a loop:
pthread_mutex_lock(&mut);
while(!ready){
pthread_cond_wait(&cond,&mut);
}
// do stuff
pthread_mutex_unlock(&mut);
The signalling thread then sets the flag before signalling:
pthread_mutex_lock(&mut);
ready=1
pthread_mutex_unlock(&mut);
pthread_cond_signal(&cond);

Mechanism of join() in multithreading

I was studying about multi-threading and came across join().
As I understand right, using join() on the thread makes process wait until 'joined' thread terminates. For example, calling t1.join() in main will make main wait until the job in thread t1 is finished and t1 terminates.
I'm just curious that how the function join() make this possible - how does it make current thread 'blocked' inside the function? Does join() force execution of joined thread first so any other thread should wait until that thread terminates? Or, is there some way to communicate between two threads(the thread who called join() and the thread who is joined)?
I will be waiting for the answer. Thanks a lot!
To be able to join you need to be able to wait on some event. Then join looks like this:
function join(t : Thread)
// do this atomically
if already done
return
wait on termination event of t
end
Waiting can be done in one of two ways:
Looping and periodically checking if the event has happened (busy wait)
Letting the system reclaim the resources of the thread and be woken up on a system event, in that case waking the thread is managed by the scheduler of the OS
It's rather language specific.
Once you create a thread, it starts running.
A join operation is when your main process stops and waits for the thread to exit and capture a return code. It will block until your thread completes - that's rather the point, as it allows for a synchronization to occur - everything in your program is at a 'known state'.
Related is the detach operation, which is effectively saying 'I don't care any more'.

How do you detect that a TEvent has been set?

The Delphi XE2 documentation says this about TEvent:
Sometimes, you need to wait for a thread to finish some operation rather than waiting for a particular thread to complete execution. To do this, use an event object. Event objects (System.SyncObjs.TEvent) should be created with global scope so that they can act like signals that are visible to all threads.
When a thread completes an operation that other threads depend on, it calls TEvent.SetEvent. SetEvent turns on the signal, so any other thread that checks will know that the operation has completed. To turn off the signal, use the ResetEvent method.
For example, consider a situation where you must wait for several threads to complete their execution rather than a single thread. Because you don't know which thread will finish last, you can't simply use the WaitFor method of one of the threads. Instead, you can have each thread increment a counter when it is finished, and have the last thread signal that they are all done by setting an event.
The Delphi documentation does not, however, explain how another thread can detect that TEvent.Set event was called. Could you please explain how to check to see if TEvent.Set was called?
If you want to test if an event is signaled or not, call the WaitFor method and pass a timeout value of 0. If the event is set, it will return wrSignaled. If not, it will time out immediately and return wrTimeout.
Having said that, the normal usage of an event is not to check whether it's signaled in this manner, but to synchronize by blocking the current thread until the event is signaled. You do this by passing a nonzero value to the timeout parameter, either the constant INFINITE if you're certain that it will finish and you want to wait until it does, or a smaller value if you don't want to block for an indefinite amount of time.

Why does my program hang when I call Free on a thread?

I dropped using FreeOnTerminate := true in favor of setting it explicitly to false, but now the code locks up every time I attempt to explicitly free the thread. I determined the lockup occurs at the Free statement.
For the last step of the thread process, I'm sending a message to a window handle I created in the main object to signal "finish." There I'm running a event, and then doing the free. Why does this happen?
I think that this is a typical multi-threading dead-lock.
When your thread sends the finish signal through sendmessage, the thread waits for the sendmessage to return before it will do anything else (e.g. the free procedure). At the same time, your main thread is waiting for the thread to free before finishing the event and processing the thread's sendmessage.
Have you tried to use postmessage instead which returns immediately and does not wait for result?

Resources