This article illustrates
that when a common resource is accessed by more than one thread its value
can be affected by all the threads during the activation time of
the threads and so the resource should be thread safe (i.e. it should be
used by only one thread at a time).
Using shared resource
resource is accessed by different threads it should
be thread safe in order to get correct results. In programming a shared resource can
be a memory location (allocated for a variable), which can be accessed by one
or more threads and it's possible to read a wrong value from the memory location when
the threads are running. Although threads do not run at the same time when a
code operation is made op of three or more instructions, due to the scheduled
time for threads, the processor may stop at the middle of an operation (for
example during an increment operation) in order to continue code execution
belonging to other threads. If then another thread gets the processor and begins
to access or check the shared resource, it will read a wrong value.
A solutions is to block access to the shared resource if it is
already in use by another thread and unblock the access when the thread is
finished to operate on the shared resource. A critical section is a mechanism
that limits access to a certain resource to a single thread in an application. A
thread enters the critical section before it needs to work the specific shared
resource and then exits the critical section after it is finished accessing the
resource. When a code section is marked by critical section only one thread at a
time is allowed to execute it.
About the Demo example
In the demo example the device context (DC) object has
been used as a shared resource among 5 different worker threads, which
try to paint the client area of the application's main window with
different colors, and it shows that the result is a multi-colored window when the threads run
without being blocked. In order to make the DC thread safe an object of
CCriticalSection class is used to block other
threads if it is already in use by another thread. The threads can be locked
and unlocked by the
member functions of the critical section object.
demo example shows that if the DC is thread safe, then the background will be painted
by only one thread at a time and the final background color is made
by the last thread and is made up of just one color.
The following image shows this
If the DC is not thread
safe every thread will have access to it during the activation time of threads
and each thread tries to paint the client area of the window with its color
and so the final background color will be made up of different colors.
image shows this situation: