TIP: Click on subject to list as thread! ANSI
echo: os2prog
to: Jon Guthrie
from: Craig Swanson
date: 1994-09-19 12:50:12
subject: threads, threads, more threads

> 2) Any variables or resources that may have to be accessed by more
 >    than one thread at a time MUST be protected by a semaphore
 >    or some other mechanism in order to avoid corrupting the data
 >    structures a thread context switch occurs such that one thread
 >    hasn't finished modifying a data structure and then the next
 >    thread starts modifying it while it is in an inconsistent state.

 JG> This is NOT correct.  While in many cases it is true that you need to use

You didn't completely read what I wrote.  I wrote "semaphore or some
other mechanism" where some other mechanism could include atomic
instructions.  I am aware of this as I've used Borland TASM for OS/2 to
write some short routines that do SMP safe atomic bit operations (test and
set, test and reset, etc.), atomic increment and test,atomic decrement and
test, and a few others.  You can't do these things in C or C++ as
efficiently as you cannot be certain of what the compiler will output. 
Moreover, there is no way to make the code SMP safe in a simple fashion as
you cannot issue LOCK prefixes on instructions except in assembler.

As you point out, simple reading and writing of 32-bit values will be
atomic.  But you should be sure to declare variables that will be accessed
in such a fashion as volatile.

 JG> protection mechanisms to prevent race conditions, it
 JG> is not ALWAYS true.  Many operations are atomic or
 JG> will not produce a race condition even if it is not
 JG> atomic.

 JG> For example, I use a variation on this code all the time:

 JG> int     thread_finished;

You should declare that thread_finished variable as volatile so that the
compiler will not optimize out the read of the memory location at which the
variable is stored.


--- Maximus/2 2.01wb

* Origin: OS/2 Connection {at} Mira Mesa, CA (1:202/354)
SEEN-BY: 12/2442 54/54 620/243 624/50 632/348 640/820 690/660 711/409 410 413
SEEN-BY: 711/430 807 808 809 934 942 712/353 623 713/888 800/1
@PATH: 202/354 301 1 3615/50 229/2 12/2442 711/409 54/54 711/808 809 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.