Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Multi-threading issues

Author: Murray

Date: 16:06:06 11/07/02

Go up one level in this thread


>>There is no problem with that.  In fact, that (global values) is the common way
>>to
>>communicate between threads.  Note that this is an SMP-implementation since it
>>depends on shared memory.
>
>What are the restrictions when using this method? Do I need to restrict myself
>to one way variables? Or should I be ok if either thread is writing and reading
>to any of the shared variables?
>

The restriction with using unsychronised global variable access is that you have
to be careful about making assumptions that normally hold true in a single
threaded environment e.g.

(global variable "a" started at 0)

if (++a == 10) ..

Normally in single threaded enviroment, the variable keeps incrementing and will
eventually reach 10 and the test will pass.

But imagine if two threads could be executing that code. One might increment a
from 9 to 10, and IMMEDIATELY the other thread might increment a from 10 to 11,
and the first one then tests if a == 10 and it fails, and the second one tests
if a == 10 and it fails. So you have to be careful about examples like that.

You also have to be careful to use atomic operations on your shared variables.
This is to prevent the varible possibly having some nasty intermediate value
during an operation that changes it. (And that is unwelcome as another thread
could read the value in it's "nasty" state.) Here is an example:
a = 100 * b / c ;
The intermediate state here is when a = 100*b, before being divided by c. During
this moment another thread could read

This doesn't mean you have to use the interlocked API's. Any simple SINGLE
operation like increment, decrement, shift, add, multiply are atomic. There's
usually no need to resort to API's or sync objects in this case.

When you DO need the interlocked APIs is when you need to know what the real
value of the variable was after this change to it. e.g. the example above with
(++a == 10) should be replaced by Interlocked API call to work properly.

Ans finally if you need to do something more complex with a variable that
requires you to prevent any chance of it being changed by another thread during
this operation, you have to resort to synchronisation objects like mutexes or
events to achieve this, but they hit performance hard.

Hope that helps
Murray





This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.