Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Semaphores?

I'm working on an implementation of the "Fair Barbershop" problem in Ruby. This is for a class assignment, but I'm not looking for any handouts. I've been searching like crazy, but I cannot seem to find a Ruby implementation of Semaphores that mirror those found in C.

I know there is Mutex, and that's great. Single implementation, does exactly what that kind of semaphore should do.

Then there's Condition Variables. I thought that this was going to work out great, but looking at these, they require a Mutex for every wait call, which looks to me like I can't put numerical values to the semaphore (as in, I have seven barbershops, 3 barbers, etc.).

I think I need a Counting Semaphore, but I think it's a little bizarre that Ruby doesn't (from what I can find) contain such a class in its core. Can anyone help point me in the right direction?

like image 813
Josh Kovach Avatar asked Mar 29 '11 20:03

Josh Kovach


People also ask

What is mutex in Ruby?

Mutex is a class that implements a simple semaphore lock for mutually exclusive access to some shared resource. That is, only one thread may hold the lock at a given time.

What are semaphores in threads?

Semaphores are typically used to coordinate access to resources, with the semaphore count initialized to the number of free resources. Threads then atomically increment the count when resources are added and atomically decrement the count when resources are removed.

Can semaphore be used for threads?

A semaphore can be configured to allow a fixed number of threads to access a resource.


3 Answers

If you are using JRuby, you can import semaphores from Java as shown in this article.

require 'java'

java_import 'java.util.concurrent.Semaphore'

SEM = Semaphore.new(limit_of_simultaneous_threads)
SEM.acquire #To decrement the number available
SEM.release #To increment the number available
like image 162
Seanny123 Avatar answered Nov 10 '22 01:11

Seanny123


There's http://sysvipc.rubyforge.org/SysVIPC.html which gives you SysV semaphores. Ruby is perfect for eliminating the API blemishes of SysV semaphores and SysV semaphores are the best around -- they are interprocess semaphores, you can use SEM_UNDO so that even SIGKILLs won't mess up your global state (POSIX interprocess semaphores don't have this), and you with SysV semaphores you can perform atomic operations on several semaphores at once as long as they're in the same semaphore set.

As for inter-thread semaphores, those should be perfectly emulatable with Condition Variables and Mutexes. (See Bernanrdo Martinez's link for how it can be done).

like image 33
PSkocik Avatar answered Nov 09 '22 23:11

PSkocik


I also found this code: https://gist.github.com/pettyjamesm/3746457

probably someone might like this other option.

like image 45
Bernardo Martinez Avatar answered Nov 10 '22 01:11

Bernardo Martinez