Re: std::string bad design????
Le Chaud Lapin wrote:
Lourens Veen wrote:
Duh. Neither will we. The point is that you could write a function
Bar, make it so that it uses a static local (global) variable,
_protect_it_using_a_mutex_, run multiple threads against it, and
watch the programme crash. I bet that that _would_ surprise you.
That depends. Mutex is only useful if concept of the class
inherently
supports multi-threading. If it does not, then synchronization will
not help. In that case, there might still be a crash even if there
is never a race condition, because again, the objects were never
meant for multiple threads.
Okay, let's try this again.
thr::mutex x_mutex;
void f() {
static int x = 42;
x_mutex.lock(); // locks mutex
int y = x;
++y;
x = y;
x_mutex.unlock(); // unlocks mutex
}
int main() {
thr::thread t1(&f); // creates thread and runs f in it
thr::thread t2(&f);
t1.join(); // waits for thread to finish executing f
t2.join();
std::cout << x << std::endl;
return EXIT_SUCCESS;
}
With the current C++ machine model, the compiler is allowed to create
code that executes the statements modifying x before it executes
x_mutex.lock(), since x_mutex can't possibly change x, and the
modification to x doesn't affect x_mutex. Thus, as far as the current
C++ standard is concerned, the above f() would be exactly equivalent
to
thr::mutex x_mutex;
void f() {
static int x = 42;
int y = x;
++y;
x = y;
x_mutex.lock();
x_mutex.unlock();
}
There is _nothing_ that a library alone can do to change this. Hence
we need changes to C++'s abstract virtual machine. Not changes to the
syntax. Not changes to the grammar. An extension to the semantics
that defines what a multi-threaded programme means.
_That_ is what I'm trying to say.
Lourens
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]