6

I searched for Bash how to create a mutex. I came across two different ways to create a mutex in Bash. Both are stackoverflow answers and both have >100 upvotes: one answer uses mkdir and the other answer uses flock.

In bash when creating a mutex, should I use flock or mkdir?

Community
  • 1
  • 1
Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177
  • 1
    Since this is kind of a meta answer over [Quick-and-dirty way to ensure only one instance of a shell script is running at a time](http://stackoverflow.com/q/185451/1983854) it might be best to open a bounty in that one, instead of having this. – fedorqui Jun 22 '16 at 13:01
  • Right now it's somewhat confusing to have two answers that implement the same thing (but different implementations) and have roughly the same number of upvotes. Depending on the outcome of this question, I will mark one of the two questions as a duplicate (with the hope being to reduce the confusion). – Trevor Boyd Smith Jun 22 '16 at 13:06

1 Answers1

8

Reading both answers it appears that both answers provide a solution for creating a mutex but there are some cases where you need to use flock and some where you need to use mkdir:

  • if you need already robust/tested features like timeout, blocking, etc etc --> use flock
    • builtin timeout
    • builtin support for blocking or nonblocking
    • builtin support for deleting the mutex after it is used
  • if your distro does not have flock --> you are forced to use mkdir
    • if you need any of the timeout or other features provided by flock you have to reinvent the wheel
    • using mkdir for creating a mutex means your code does not convey the purpose immediately --> whereas using flock means your code speaks for itself saying "this code is implementing synchronization"
    • most people aren't familiar with mkdir being a valid solution for creating a mutex and so using mkdir in this way may make your code have more code smell (especially if your distro has flock available and you choose not to use it)
Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177