Article View: borland.public.cppbuilder.nativeapi
Article #7544Re: Accessing same variable from multiple threads
From: Remy Lebeau (TeamB)
Date: Wed, 19 Jan 2005 17:39
Date: Wed, 19 Jan 2005 17:39
46 lines
2093 bytes
2093 bytes
"Tumurbaatar S." <nospam_tumur@magicnet.mn> wrote in message
news:41edea6b@newsgroups.borland.com...
> Is it not matter that I'm not using any synchronization methods?
Yes, it does matter. Always synchronize accees to any data that is shared
by multiple threads, especially if one of the threads is altering the data.
In this particular case, the easiest way to synchronize access to a shared
integer is to use the Interlocked functions, such as InterlockedExchange and
InterlockedExchangeAdd():
int my_var = 0;
--- thread1 ---
InterlockedExchange(&my_var, new_value);
--- thread2 ---
if( InterlockedExchangeAdd(&my_var, 0) != 0 ) ...
Otherwise, use a critical section instead:
int my_var = 0;
CRITICAL_SECTION cs = {0};
--- program startup ---
InitializeCriticalSection(&cs);
--- program termination ---
DeleteCriticalSection(&cs);
--- thread1 ---
EnterCriticalSection(&cs)
my_var = new_value;
LeaveCriticalSection(&cs)
--- thread2 ---
EnterCriticalSection(&cs);
if( my_var != 0 ) ...
LeaveCriticalSection(&cs);
Gambit
Technical Details
Message-ID:
<41ee9aae$1@newsgroups.borland.com>Path:
arc1-ca.pugleaf.net!g2news1.google.com!news1.google.com!news2.google.com!proxad.net!213.200.89.82.MISMATCH!tiscali!newsfeed1.ip.tiscali.net!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!newsgroups.borland.com!not-for-mailReferences:
<41edea6b@newsgroups.borland.com>Show Full Headers
Complete Article Headers
X-Google-Thread: 10cc67,4809cdd9a7828fa7 X-Google-Attributes: gid10cc67,public X-Google-Language: ENGLISH,ASCII-7-bit From: "Remy Lebeau \(TeamB\)" <no.spam@no.spam.com> Newsgroups: borland.public.cppbuilder.nativeapi References: <41edea6b@newsgroups.borland.com> Subject: Re: Accessing same variable from multiple threads Date: Wed, 19 Jan 2005 09:39:02 -0800 Lines: 48 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 6.00.2800.1409 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1409 NNTP-Posting-Host: 68.69.17.41 Message-ID: <41ee9aae$1@newsgroups.borland.com> X-Trace: newsgroups.borland.com 1106156206 68.69.17.41 (19 Jan 2005 09:36:46 -0800) Path: arc1-ca.pugleaf.net!g2news1.google.com!news1.google.com!news2.google.com!proxad.net!213.200.89.82.MISMATCH!tiscali!newsfeed1.ip.tiscali.net!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!newsgroups.borland.com!not-for-mail