views:

72

answers:

2

Hi,

I am asking question about multithreading in general. For example I locked a mutex and resume the task, then I want to suspend it, my question is, should I unlock the mutex before suspending it? So that when I resume it again with mutex it will resume successfully?

I just got started in multithreaded stuff and I am having a hard time figuring out the concepts.

Many thanks.

+2  A: 

Generally you want to hold a mutex as long as you need "mutually exclusive" control of whatever it is you're synchronizing on. I would say it's gonna be problematic to keep grabbing,releasing it. Maybe a fuller explanation of what you're doing? My approach is to do things asynchronously rather than multi-threaded. Often a better use of system resources.

No Refunds No Returns
What do you mean asynchronously? Is multithreading is a asychronous implementation?
sasayins
+1  A: 

No. You should hold the mutex, even when the task is suspended.

The mutex is there to protect a section of code from multiple threads accessing it at the same time. If you release the mutex when you suspend, this allows another thread to access that section of code which is what the mutex is there to prevent.

If you feel that the mutex does not need to be held, it indicates that you need to re-design when the mutex locks are taken and released (based on what you are trying to protect). This should be independent of the resume/suspend of the threads.

Jeremy Simon