Re: Thread mess
On Jun 22, 11:27 pm, Maxim Yegorushkin <maxim.yegorush...@gmail.com>
wrote:
On Jun 21, 1:27 pm, wasti.r...@gmx.net wrote:
On Jun 20, 9:38 pm, kalman <mend...@gmail.com> wrote:
Hi all,
I've recently stepped in a project of medium size, and at the easy
question: "are those class instances shared between two or more
threads" the response was: "no... wait... yes, well I'm not sure... I
don't know...". Riiiight.
I used the following technique that should permit to detect (at
runtime, sigh!) if two or more threads are using concurrently a class.
I think the approach is faulty. If you want to know if an instance is
used by more than one thread, you shouln't rely on it being actually
used concurrently in one particular execution - threading being what
it is, you might miss the shared usage.
Instead, remember the current thread ID in the constructor and never
reset it. Test at every function entry. This way you'll definitely see
if more than one thread accesses an instance during its lifetime, even
if the accesses happen to not occur at exactly the same time.
The global objects are initialised by the thread that enters main()
(in a typical implementation). If some global objects are only ever
used by another thread this approach may not work.
In that case you can set the watches like this:
class MayBeShared {
MayBeShared() {
WATCH(ctor_dtor)
...
}
~MayBeShared() {
WATCH(ctor_dtor)
...
}
foo() {
WATCH(unic_thread)
...
}
bar() {
WATCH(unic_thread)
...
}
do_some_work() {
WATCH(multiple_thread_external_sync_mechanism)
...
}
private:
THREAD_WATCH(ctor_dtor)
THREAD_WATCH(unic_thread)
THREAD_WATCH(multiple_thread_external_sync_mechanism)
};
the "ctor_dtor watch" checks that the instances are created and
destroyed on same thread,
the "unic_thread watch" checks that a single thread ever is using
those methods while
the "multiple_thread_external_sync_mechanism watch" checks that class
external synchronization
mechanism are working or in place.
Consider this case:
class SharedForSure
{
foo() {
Mutex::scoped_lock lock(theMutex);
theClassToProtect.do_some_work();
}
bar() {
<=== Here is missing a lock
theClassToProtect.do_some_work();
}
private:
MayBeShared theClassToProtect;
Mutex theMutex;
};
the class SharedForSure has a bug missing a lock on his public bar
method,
hence the instance of MayBeShared can detect (if happens) the wrong
usage.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]