boost::condition_variable thread safety? - thread-safety

This boost example on condition variables shows that the mutex does not have to to held during the call to cond.notify_one(). Does this imply that boost::condition_variable is thread-safe? i.e. what happens if the "prepare data" thread releases the mutex and attempts to call cond.notify_one(), while the other thread now acquires the released mutex and simultaneously attempts the call to cond.wait(...)?

That example does not imply that boost::condition_variable is thread safe. Nevertheless, wait, wait_for, wait_until, notify_one and
notify_all are thread safe member functions.
Boost.Thread documents its conformance and extension of the C++11 standard Thread library. It lists Condition variables, Class condition_variable, and Class condition_variable_any to be in compliance.
The relevant part of the standard (ยง 30.5-2) states:
Condition variables permit concurrent invocation of the wait, wait_for, wait_until, notify_one and notify_all member functions.

Related

Can a thread call SuspendThread passing its own thread ID?

Can a Windows thread suspend itself with SuspendThread()?
I can awake it from another one but, can it call SuspendThread(GetCurrentThreadId())?
It seems this is possible, but with a slight alteration (see the cygwin mailing list discussing this here):
SuspendThread(GetCurrentThread());
I also found MSDN saying a thread should only suspend itself, but it doesn't make it clear for me. I quote (from here, emphasis mine):
This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.
Yes, you can use SuspendThread on current thread. Good read on the topic.
As a method of creating reusable threads for work tasks without the overhead of create and terminate tasks, suspend and resume thread could be used to quiesce a thread at the end of the task. When work is dispatch to the thread, resume it.

pthread_mutex_lock() and EnterCriticalSection

may be I misunderstood something but...
When I call pthread_mutex_lock() and then call pthread_mutex_lock() out of the same thread again without calling pthread_mutex_unlock(), the second call of pthread_mutex_lock() will block.
But: when I call EnterCriticalSection() and call EnterCriticalSection() out of the same thread again without calling LeaveCriticalSection(), the second call of EnterCriticalSection() will NOT block since it is called out of the same thread (what is a very weird behaviour for me).
So my question is there a WinAPI function available that behaves like pthread_mutex_lock() and locks independent from the thread context?
I'm aware of libpthread for Windows but I prefer to have a WinAPI function here.
You could use a Semaphore with the maximum count set to one.
See Semaphore Objects
When you successfully acquire the semaphore, its count is decremented: going to zero in our case.
No other thread can acquire it, including the current one.
pthread_mutex_lock documentation:
If the mutex type is PTHREAD_MUTEX_RECURSIVE, then the mutex maintains the concept of a lock count. When a thread successfully acquires a mutex for the first time, the lock count is set to one. Every time a thread relocks this mutex, the lock count is incremented by one. Each time the thread unlocks the mutex, the lock count is decremented by one. When the lock count reaches zero, the mutex becomes available for other threads to acquire. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error will be returned.
MSDN ReleaseMutex states:
A thread can specify a mutex that it already owns in a call to one of the wait functions without blocking its execution. This prevents a thread from deadlocking itself while waiting for a mutex that it already owns. However, to release its ownership, the thread must call ReleaseMutex one time for each time that it obtained ownership (either through CreateMutex or a wait function).
The wait functions are the equivalent to pthread_mutex_lock.
See Mutex Objects (Windows) to get more details about this API.
And this stackoverflow entry to see what the CRITICAL_SECTION object contains. This will disclose
that the CRITICAL_SECTION object holds - among others - a value LockCount to allow recursive use. See the EnterCriticalSection function to learn about this feature.

MFC CEvent class member function SetEvent , difference with Thread Lock() function?

what i s the difference between SetEvent() and Thread Lock() function? anyone please help me
Events are used when you want to start/continue processing once a certain task is completed i.e. you want to wait until that event occurs. Other threads can inform the waiting thread about the completion of this task using SetEvent.
On the other hand, critical section is used when you want only one thread to execute a block of code at a time i.e. you want a set of instructions to be executed by one thread without any other thread changing the state at that time. For example, you are inserting an item into a linked list which involves multiple steps, at that time you don't want another thread to come and try to insert one more object into the list. So you block the other thread until first one finishes using critical sections.
Events can be used for inter-process communication, ie synchronising activity amongst different processes. They are typically used for 'signalling' the occurrence of an activity (e.g. file write has finished). More information on events:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686915%28v=vs.85%29.aspx
Critical sections can only be used within a process for synchronizing threads and use a basic lock/unlock concept. They are typically used to protect a resource from multi-threaded access (e.g. a variable). They are very cheap (in CPU terms) to use. The inter-process variant is called a Mutex in Windows. More info:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682530%28v=vs.85%29.aspx

Mutex vs Event in Windows

can somebody please explain what is the difference if I do
mutex = createMutex
waitForSingleObject
Release(mutex)
and
event = createEvent
waitForSingleObject
Release(event)
I'm so confused, can I use both versions for the synchronization? thanks in advance for any help
You use a mutex to ensure that only one thread of execution can be accessing something. For example, if you want to update a list that can potentially be used by multiple threads, you'd use a mutex:
acquire mutex
update list
release mutex
With a mutex, only one thread at a time can be executing the "update list".
You use a manual reset event if you want multiple threads to wait for something to happen before continuing. For example, you started multiple threads, but they're all paused waiting for some other event before they can continue. Once that event happens, all of the threads can start running.
The main thread would look like this:
create event, initial value false (not signaled)
start threads
do some other initialization
signal event
Each thread's code would be:
do thread initialization
wait for event to be signaled
do thread processing
Yes, both can be used for synchronization but in different ways.
Mutex is a mutual exclusion object and can be acquired only by a single instance at a time. It is used to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code
Event is an objet that can be explicitly set to a state by use of the SetEvent function.

Recycle-safe thread ID's and when thread stack gets freed?

Does the stack reserved/commited for a thread get freed when
the thread terminates
the thread object is destroyed
(i.e. the thread is terminated and all handles to the thread are closed)
?
More broadly, are there significant resources associated with a thread that has terminated, but still exists since there are valid handles to it?
Reason: I need to modify a kind of "scoped singleton", so it doesn't return a single object, but a per-thread object. I cannot rely on thread creation/termination notices, much less on process-wide ones.
At the moment, I store the objects in a map<ThreadID, Object>, with a cache cleanup policy that's suitable for my application. To protect myself from the OS "recycling" thread ID's, I keep an handle to the thread open. (Rec
A side effect would be holding open handles to long-terminated threads in some corner cases.
According to "Windows VIA C/C++" by Richter and Nasarre (A must-have book for any C++ Windwos programmer) p.154:
Terminating a Thread
A thread can be terminated in four
ways:
The thread function returns. (This is highly recommended.)
The thread kills itself by calling the ExitThread function. (Avoid this
method.)
A thread in the same process or in another one calls the TerminateThread
function. (Avoid this method.)
The process containing the thread terminates. (Avoid this method.)
The Thread Function Returns
You should always design your thread
functions so that they return when you
want the thread to terminate. This is
the only way to guarantee that all
your thread's resources are cleaned up
properly.
Having your thread function return
ensures the following:
All C++ objects created in your thread function will be destroyed
properly via their destructors.
The operating system will properly free the memory used by the thread's
stack.
The system will set the thread's exit code (maintained in the thread's
kernel object) to your thread
function's return value.
The system will decrement the usage count of the thread's kernel object.
The ExitThread Function
You can force your thread to terminate by having it call ExitThread:
VOID ExitThread(DWORD dwExitCode);
This function terminates the thread
and causes the operating system to
clean up all the operating system
resources that were used by the
thread. However, your C/C++ resources
(such as C++ class objects) will not
be destroyed. For this reason, it is
much better to simply return from your
thread function instead of calling
ExitThread yourself.
Of course, you use ExitThread's
dwExitCode parameter to tell the
system what to set the thread's exit
code to. The ExitThread function does
not return a value because the thread
has terminated and cannot execute any
more code.
Note The recommended way to have a
thread terminate is by having its
thread function simply return (as
described in the previous section).
However, if you use the method
described in this section, be aware
that the ExitThread function is the
Windows function that kills a thread.
If you are writing C/C++ code, you
should never call ExitThread. Instead,
you should use the C++ run-time
library function _endthreadex. If you
do not use Microsoft's C++ compiler,
your compiler vendor will have its own
alternative to ExitThread. Whatever
this alternative is, you must use it.
The TerminateThread Function
A call to
TerminateThread also kills a thread:
BOOL TerminateThread( HANDLE
hThread, DWORD dwExitCode);
Unlike ExitThread, which always kills
the calling thread, TerminateThread
can kill any thread. The hThread
parameter identifies the handle of the
thread to be terminated. When the
thread terminates, its exit code
becomes the value you passed as the
dwExitCode parameter. Also, the
thread's kernel object has its usage
count decremented.
Note The TerminateThread function is
asynchronous. That is, it tells the
system that you want the thread to
terminate but the thread is not
guaranteed to be killed by the time
the function returns. If you need to
know for sure that the thread has
terminated, you might want to call
WaitForSingleObject or a similar function,
passing the handle of the thread.
A well-designed application never uses
this function because the thread being
terminated receives no notification
that it is dying. The thread cannot
clean up properly, and it cannot
prevent itself from being killed.
Note When a thread dies by returning
or calling ExitThread, the stack for
the thread is destroyed. However, if
TerminateThread is used, the system
does not destroy the thread's stack
until the process that owned the
thread terminates. Microsoft purposely
implemented TerminateThread in this
way. If other still-executing threads
were to reference values on the
forcibly killed thread's stack, these
other threads would raise access
violations. By leaving the killed
thread's stack in memory, other
threads can continue to execute just
fine.
In addition, dynamic-link libraries
(DLLs) usually receive notifications
when a thread is terminating. If a
thread is forcibly killed with
TerminateThread, however, the DLLs do
not receive this notification, which
can prevent proper cleanup.
When a Thread Terminates
The following actions occur when a
thread terminates:
All User object handles owned by the
thread are freed. In Windows, most
objects are owned by the process
containing the thread that creates the
objects. However, a thread owns two
User objects: windows and hooks. When
a thread dies, the system
automatically destroys any windows and
uninstalls any hooks that were created
or installed by the thread. Other
objects are destroyed only when the
owning process terminates.
The thread's exit code changes from
STILL_ACTIVE to the code passed to
ExitThread or TerminateThread.
The state of the thread kernel object
becomes signaled.
If the thread is the last active
thread in the process, the system
considers the process terminated as
well.
The thread kernel object's usage count
is decremented by 1.
When a thread terminates, its
associated thread kernel object
doesn't automatically become freed
until all the outstanding references
to the object are closed.
Once a thread is no longer running,
there isn't much any other thread in
the system can do with the thread's
handle. However, these other threads
can call GetExitCodeThread to check
whether the thread identified by
hThread has terminated and, if it has,
determine its exit code:
BOOL GetExitCodeThread( HANDLE
hThread, PDWORD pdwExitCode);
The exit code value is returned in the
DWORD pointed to by pdwExitCode. If
the thread hasn't terminated when
GetExitCodeThread is called, the
function fills the DWORD with the
STILL_ACTIVE identifier (defined as
0x103). If the function is successful,
TRUE is returned.
Maybe you should use pthread_getspecific, pthread_setspecific and pthread_key_create to manage your per thread singleton.

Resources