Re: synchronization on static bool
- From: "Doug Harrison [MVP]" <dsh@xxxxxxxx>
- Date: Sat, 03 Dec 2005 12:43:22 -0600
On 3 Dec 2005 10:12:36 -0800, mwpa@xxxxxxxxx wrote:
>Hello,
>
>I'm using AfxBeginThread to start thread(and threre check is
>running==false), when I want to stop this thread I'm setting
>running=false, from another thread:
>
>static bool running;
>
>void MainThread()
>{
> running = true;
> CWinThread *thr = AfxBeginThread(worker,abc);
> {
> //do something, long time and after all stop worker thread
> running =false;
> }
>}
>
>UINT worker(LPVOID me)
>{
> while(true){
> if(!running)break;
> }
>}
>
>Is this solution correct? (Some weakness?)
For instructions on using CWinThread safely and a comparison of using bool
vs. an event object, see:
http://members.cox.net/doug_web/threads.htm
If you decide to stick with the bool, do declare it volatile. This will
prevent the compiler from caching its value in a register, which absent
volatile, it may do if it determines the variable cannot be modified (by
the current thread - the compiler assumes single-threading) between two
accesses of it. Besides volatile, what would prevent the compiler from
drawing such a conclusion? The main thing would be calling a function
between the two accesses that it cannot see into, such as a function
residing in an opaque DLL; the compiler would have to consider the bool
reachable from such a function. Being synchronization objects, event
objects don't have this problem. But note that this is sort of an abuse of
volatile, for the reasons given in these messages:
http://groups.google.com/groups?selm=7hl7205u4ksejokc9ormufeo02pb9i1stu%404ax.com
http://groups.google.com/groups?selm=k7fa209epgjcn2rep0rqks2ee0f4jcitgu%404ax.com
--
Doug Harrison
Visual C++ MVP
.
- Follow-Ups:
- Re: synchronization on static bool
- From: Alexander Grigoriev
- Re: synchronization on static bool
- References:
- synchronization on static bool
- From: mwpa
- synchronization on static bool
- Prev by Date: Re: setpassword and xp styles?
- Next by Date: Re: MFC future?
- Previous by thread: synchronization on static bool
- Next by thread: Re: synchronization on static bool
- Index(es):
Relevant Pages
|