Re: C++ Threads, what's the status quo?
Le Chaud Lapin wrote:
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 increment has no visible side effects, so the compiler is not
obliged to sandwich it between the acquire and the release. How do you
ensure that the compiler won't do either of those?
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.
And, again, how do you ensure that the compiler won't do the increment
before the call to enter or after the call to leave?
--
-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]