Re: [OT] Critical section ?
From: Andrey Tarasevich (andreytarasevich_at_hotmail.com)
Date: 12/21/04
- Next message: Chris \( Val \): "Re: using namespace std; discussion"
- Previous message: Edd: "Re: pesky Pointers !!"
- In reply to: James: "Critical section ?"
- Next in thread: James: "Re: [OT] Critical section ?"
- Reply: James: "Re: [OT] Critical section ?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 20 Dec 2004 17:37:08 -0800
James wrote:
> I recently was asked to answer this
>
> int g_nNums[100]
>
> DWORD WINAPI Thread(LPVOID lpvParams)
> {
> int iIndex = some value;
>
> EnterCriticalSection(g_CriticalSection);
>
> if( g_Nums[nIndex] < MIN_VAL)
> IncrementIndex(iIndex);
> else
> g_nNums[iIndex] = MIN_VAL;
>
> LeaveCriticalSecton(&g_CriticalSection);
>
> return 0;
> }
>
> void IncrementIndex(int iIndex)
> {
> ...
> g_nNums[nIndex++];
Did you mean 'g_nNums[nIndex]++'?
> ...
> }
>
>
> How can IncrementIndex be written so that it is thread safe and won't
> deadlock?
In the above portion of code 'IncrementIndex' is called from inside a
block of code protected by a Enter/LeaveCriticalSecton calls. If this
function will always be called from such protected blocks, there's no
need to take any additional steps to make it thread safe.
> I answered that I would wrap it in a critical seciton or a mutex. What are
> the potential problems with that answer ?
If you need to make this function thread safe by itself, wrapping its
body in a CS will work.
However, it looks like this function is intended to work with a _group_
(an array) of indices. It you simply wrap the entire function in a CS,
it will always block all access to all indices at once. This is probably
OK with such a quick operation as modification of an index, but might be
unacceptable for some more complex action (i.e. when the CS remains
occupied for long periods of time). In such cases one might consider
implementing some data-based locking technique (not the code-based one
as the above CS) that will protected only one element of the array - the
one being accessed by this thread, leaving other elements accessible to
other threads.
Another direction worth considering is distinguishing between modifying
and non-modifying type of access, i.e. using read/write locks.
-- Best regards, Andrey Tarasevich
- Next message: Chris \( Val \): "Re: using namespace std; discussion"
- Previous message: Edd: "Re: pesky Pointers !!"
- In reply to: James: "Critical section ?"
- Next in thread: James: "Re: [OT] Critical section ?"
- Reply: James: "Re: [OT] Critical section ?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|