Multi Threading Flashcards
How to create a new thread in ruby?
Thread.new { p ‘hello’ }
Thread.new { p ‘hello2’ }
Why do we need Mutex? And how to create it?
Mutex allows us to synchronize the two threads
that we have created so that one thread does not access other threads resources when the other is in the middle of some busy process.
mutex = Mutex.new
Thread.new {
mutex.synchronize do
# …
end
}
Thread.new {
mutex.synchronize do
# …
end
}
What is deadlock?
A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish.
What is Concurrency? What is Parallelism? And differences?
- Concurrency is the ability to manage many tasks simultaneously (Many tasks but not all together)
- Parallelism is doing multiple tasks at exactly
the same time. ( All tasks together )
What is race condition?
A race condition occurs when two or more threads can access shared data and they try to change it at the same time
What is a trade-safe application?
When an application is thread-safe, it can work in a multi-
threaded environment without any of those haunting side effects.
What is GIL?
A global interpreter lock (GIL) is a mechanism used in computer-language interpreters to synchronize the execution of threads so that only one native thread can execute at a time
Ruby switches between threads as needed, but only one is being executed.
What is fork/wait logic?
—–
child = fork do
sleep 3
puts “Child says ‘hi’!”
end
puts “Waiting for the child process…”
Process.wait child
puts “All done!”
Waiting for the child process…
<3 second delay>
Child says ‘hi’!
All done!
How to run the thread?
thread = Thread.new { p ‘hello’ }
thread.run
# or
thread.join
How to set timeout for the thread?
thread = Thread.new { p ‘hello’ }
thread.join(1) # 1 second timeout
What is Fibers?
In short, fibers are pragmatically similar to threads, but fibers aren’t scheduled to all run together. You have to manually control the scheduling.
Can you provide an example of Fiber?
goes to each breakpoint in resume it
sg = Fiber.new do
s = 0
# infinity loop
loop do
square = s * s
# fiber set breackpoint
Fiber.yield square
s += 1
end
end
10.times { puts sg.resume }
# shows only 10 results
How to get a list of all running Threads?
Thread.new { sleep 10 }
Thread.new { x = 0; 10000000.times { x += 1 } }
Thread.new { sleep 100 }
Thread.list