Re: C++ Threads, what's the status quo?
Pete Becker wrote:
Le Chaud Lapin wrote:
I have been saying all along. We should stop doing X and hoping that
things will work out magically. To do mutual exclusion, you need
low-level support.
And nobody has disagreed with you. But let's get down to the nub of the
matter:
static long counter;
Please write a function that increments the value of this static
variable and can be called safely from multiple threads. Use whatever
low level support you need, but state explicitly what that support is.
There are two ways to do this: one using a mutex, the other using a
critical section. Assuming the underlying OS is Windows:
The mutex is simpler but slower:
Mutex counter_mutex; // global
void increment_counter ()
{
counter_mutex.acquire();
++count;
counter_mutex.release();
}
The class Mutex would be a wrapper that contains a Windows handle to a
kernel-mode mutex. The constructor would call CreateMutex with no
name. acquire() and release() would be calls to WaitForSingleObject and
ReleaseMutex respectively.
The other method would be to use a critical section. It is
stochastically faster than a mutex because it uses a user-mode
spin-lock to make quick attempt to grab exclusivity before going into
kernel-mode, but then you must surrender strict portability of the
header file, which might have been possible with a mutex.
void increment_count()
{
Critical_Section cs; // constructor calls
InitializeCriticalSection();
cs.enter(); // EnterCriticalSection();
++count;
cs.leave(); // LeaveCriticalSection();
// ~cs calls DeleteCriticalSection();
}
would be the function set used.
The assumptions I would make about the operating system is that it:
1. Provides a kernel-mode mutex
2. Provides atomic test and set, swap, or other operation to implement
the user-mode spin-lock inside the critical section.
The most important statement I can make about this example is that I
would not regard the global variable counter as being "special" simply
because it is a scalar. If it is to be operated upon by multiple
threads simultaneously, it will require the same treatment as say, a
POD object that consumes 8192 bytes, and protect it with a critical
section or mutex.
-Le Chaud Lapin-
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]