What is the best way to wait for a variable in a m

2019-04-21 18:48发布

I would like to do something like the below for a multi-threaded program:

// wait for variable to become true but don't hog resources  
// then re-sync queues  

Is something like this a good solution?

while (!ready) {
    Thread.Sleep(250); // pause for 1/4 second;
};

8条回答
做自己的国王
2楼-- · 2019-04-21 19:45

Granted this is C#, but I've found this book to be extremely helpful for doing multi-threading development.

http://www.albahari.com/threading/

Some of the info is not language specific.

查看更多
戒情不戒烟
3楼-- · 2019-04-21 19:54

On top of good answers already provided - you will waste half the sleep time, assuming a random distribution of the occurrence you wish to detect. 125ms is an eternity in computer time.

WaitForSingleObject on a Win32 Event handle allows you to detect the required signal pseudo-immediately (depending on what other threads in your process are doing), and not do redundant checks (how many needless loops do you have to execute before the signal arrives?), provided the setting thread call SetEvent once it's done with its work. The bool is then redundant, which is as it should be.

查看更多
登录 后发表回答