views:

86

answers:

5

Hello,

I was wondering whether it would ever make sense to use a mutex or semaphore when there is only one thread?.

Thanks for your help.

+1  A: 

Mutex can make sense, since Mutex can be used for system wide sharing, instead of internal process-wide sharing. For example, you can use a Mutex to prevent an application from being started twice.

Reed Copsey
+1  A: 

This may be a bit out there but lets say you are writing a recursive function and you want each level to register with a separate resource. This way you can keep the responsibility of cleaning up the resource in one place (The resource pool).

ChaosPandion
In a truly single threaded app, though, there's probably better options for this...
Reed Copsey
@Reed - I am sure of it, that's why I added my little disclaimer.
ChaosPandion
+1  A: 

Sounds like a trick question. Technically, yes. A named mutex can be used to synch multiple processes containing a single thread in each.

P.Brian.Mackey
+3  A: 

I design thread protection into my components because they are reusable and scalable components intended to work in any environment I can realistically anticipate. Many times they are initially used in a single thread environment. Often times the scope of the implementation expands to include more threads. Then I don't have to chase down resources to protect from the new access scenarios.

Amardeep
Yep, it is always a good idea to think ahead with regards to concurrency.
ChaosPandion
Yes, this is the problem I am facing. At the moment my program is single-threaded, but it is highly likely that there will be multiple threads in the future ...
Mewzer
+1  A: 

You can use system-wide semaphores (and even mutexes) to do inter-process communication.

You can signal from a single-threaded process to another single-threaded process by acquire()/release()-ing on a named semaphore, for example.

the_void