Terms in Ruby Concurrency

05 Jul 2020

Threads Pro and Con

Benefits:

  • Higher throughput
  • Responsive applications
  • Efficient utilization of resources

Problems:

  • Touch to find bugs
  • Higher cost of code maintenance
  • Increased utilization of system resources
  • Programs may experience slowdown

When to use thread and when not?

Thread suit for IO bind problems but not suit for CPU bind problems

Why ruby concurrency is hard?

It’s a MRI’s problem. Global Interpreter Lock makes it hard.

Throughput and latency

Throughput and latency have an inverse relationship

Race condition

It’s about which thread will finish first.

How to write mutex?

semaphore = Mutex.new

a = Thread.new do
  semaphore.synchronize do
    # ...
  end
end

b = Thread.new do
  semaphore.synchronize do
    # ...
  end
end

Synchronize

Obtain a lock, runs the block, and releases the lock when the block completes.

Liveness

The ability of a program to execute in a timely manner.

Multithread bad situation

  • Deadlock
  • Live-Lock: similar to deadlock
  • Starvation: a thread never gets CPU time or access to a shared resources

Reentrant-Lock

Allow for re-locking or re-entering of a synchronization lock

Mutext vs Semaphore

The number of threads can call acquire and release on it

  • Mutext is 1
  • Semaphore is multiple

Signal (comunication)

  • Mutext can’t signal
  • Semaphore can signal

Monitor

Monitor is a mutext with a wait set.

How to create thread in Ruby?

  • new
  • start
  • fork

Thread priority

Thread has priority: threaad.priority = 2

Back to top