Tuesday 15 June 2010

multithreading - CSemaphore in MFC C++ doesn't work -



multithreading - CSemaphore in MFC C++ doesn't work -

i'm trying create semaphore multiple threads, need run 1 thread @ time. i'm declaring semaphore in dialog file

ghsemaphore = createsemaphore(null, 1, 1, null); // 1 thread @ 1 time

before start tread call

waitforsingleobject(ghsemaphore, 0l);

before thread ends call:

releasesemaphore(ghsemaphore, 1, null);

it starts treads instead of 1 tread once. thought please ? lot!

you "before start thread..(you acquire semaphore)" - in same (main) thread? think, semaphore restrict acquisition one thread (which here main thread), acquisition needed placed within (child) threads, allow 1 of them run concurrently.

you have create single 1 semaphore in parent thread , pass reference kid threads. 1 time 1 kid thread released wait..() semaphore blocks concurrent threads until first 1 releases semaphore , next kid thread allowed run. however, kid threads run concurrently until phone call of wait..().

btw: why create multiple threads if want 1 thread run @ time (until terminates)?

regarding scope create semaphore: info provided looks ok have 1 single semaphore @ application level. however, recommend pass kid threads parameter @ thread start (instead of referring global variable), kid threads independent of selection of scope. if ever need handle multiple, independent bunches of such kid threads, can switch create 1 semaphore each bunch before created (the other alternative mentioned). if create semaphores on fly, sure release it, 1 time threads have terminated.

so, now, best create 1 application-wide semaphore ("global").

multithreading

No comments:

Post a Comment