Paul Braman
2004-09-10 13:45:16 UTC
Consider this example program...
The main thread starts, creates a worker thread, waits for some
signal, then terminates the worker thread before rejoining it and
exiting.
In my "keep it simple" mindset, I figure that if I just pass the
thread a boolean flag and set the flag in the main thread when the
worker needs to exit, the worker can be pretty simple:
void * worker (void * data)
{
bool * done = (bool *)data;
while (! *done)
{
// ...
}
return NULL;
}
As long as it can periodically check the flag I should be set. I do
have some comments/questions about this as it relates to real MT
programming.
1) Since I'm really just using the boolean as a flag, do I *really*
need to synchronize access to it via a mutex?
2) If I don't need to synchronize access to it, should I be declaring
it volatile since it will be manipulated randomly outside the scope of
the worker function?
3) Is there a better pattern for this kind of signaling?
Maybe this seems like a pretty basic problem, but after reading Herb
Sutter's article in C/C++ Users Journal about thread-safety sometimes
being "good enough", I'm going back and rethinking my ideas on things.
Thanks!
Paul Braman
Paul<dot>Braman<at>NielsenMedia<dot>com
The main thread starts, creates a worker thread, waits for some
signal, then terminates the worker thread before rejoining it and
exiting.
In my "keep it simple" mindset, I figure that if I just pass the
thread a boolean flag and set the flag in the main thread when the
worker needs to exit, the worker can be pretty simple:
void * worker (void * data)
{
bool * done = (bool *)data;
while (! *done)
{
// ...
}
return NULL;
}
As long as it can periodically check the flag I should be set. I do
have some comments/questions about this as it relates to real MT
programming.
1) Since I'm really just using the boolean as a flag, do I *really*
need to synchronize access to it via a mutex?
2) If I don't need to synchronize access to it, should I be declaring
it volatile since it will be manipulated randomly outside the scope of
the worker function?
3) Is there a better pattern for this kind of signaling?
Maybe this seems like a pretty basic problem, but after reading Herb
Sutter's article in C/C++ Users Journal about thread-safety sometimes
being "good enough", I'm going back and rethinking my ideas on things.
Thanks!
Paul Braman
Paul<dot>Braman<at>NielsenMedia<dot>com