3

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.

Umbungu
  • 945
  • 3
  • 10
  • 30

6 Answers6

5

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 AC9MF
  • 18,464
  • 5
  • 40
  • 50
  • 1
    Yep, it is always a good idea to think ahead with regards to concurrency. – ChaosPandion Jun 21 '10 at 20:46
  • 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 ... – Umbungu Jun 21 '10 at 20:47
1

In case the environment supports system interrupts it adds non-linear behaviour. Semaphore can be used in order to sleep in main thread until interrupt triggers.

1

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
  • 554,122
  • 78
  • 1,158
  • 1,373
1

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
  • 77,506
  • 18
  • 119
  • 157
1

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
  • 43,228
  • 68
  • 238
  • 348
1

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
  • 5,512
  • 2
  • 28
  • 34