开发者

how to access shared resource between 2 threads?

In one of Outlook add in, I have a worker thread that does some processing and then updates a boolean flag. Main thread checks this flag and if this is false , it just process a while loop and does nothing.

 
//worker thread 
void DoSoneThing()
{
Outlook.Recipients recps = mail.Recipients.
foreach(Outlook.Recipient recp in recps)
{
//Save each recipients in a colection
}
isDone=true;
}


//Main thread
while(!isDone)
{
/开发者_如何转开发/read the collection where recipients name have been stored.
}``

if the Main thread comes to this piece of code before the worker thread has set the flag to true, main thread keeps on processing the loop and secondry thread is just kind of paused. and since the isDone flag is never set to true, main thread doesn't do any thing.

When I put a lock in the DoSomeThing method and used the same lock in mian thread, this issue is resolved.

myClass
{
public static object _syncRoot = new Object();
void DoSoneThing()
{
lock(_syncRoot)
{
//process 
isDone=true;
}
}
}

myOtherClass
{
    lock(myClass._syncRoot)
{
//process
}
}

My understanding was that lock is used to restrict the entry to same piece of code by more than one thread. But don't understand why worker thread doesn't do any thing when shared resource is accessed by main thread.


I think there is likely to be a slight conceptual problem here.

Firstly can I suggest that the

while(!isDone)

is not a great way of waiting - It's known as 'spinning' and allows the thread to use processor time when it's not doing anything, which is not efficient. (Spinning on a lock can be ok in some specific circumstances, but in a user app is generally not a good plan.)

The lock, making one thread wait while the other processes is much better.

Now, as to your specific problem. It's possible that the isDone flag read in the while test has been optimised out (i.e. the compiler 'knows' that it isn't going to change, so it doesn't put in any code to get it from memory again - it just tests the same CPU register.) You can overcome this by using the 'volatile' modifier to tell the compiler it must re-get the value from memory. It's also possible that the main thread, spinning, is starving the other thread so it never gets a chance to set the flag (although one would hope it would eventually, in a 'fair' system.)

Regardless of the latter, having a thread spin while waiting for another thread to finish proccessing is to be avoided, unless having checked the flag, it goes off to do something useful (such as updating the GUI) instead.

You need to be very careful with multi-threaded designs - they're intricate and can have obscure and hard-to-predict behaviour (but are well worth doing for the right circumstances.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜