Threads and Locks

It is not likely that you will be asked a question on threads even a big tech company unless the team uses threads regularly, but some general understanding of threads and deadlocks is typical for a developer.

Threads and Processes

A process is a collection of code, memory, data, and other resources. A thread is a sequence of code that is executed within the scope of the process. You can (usually) have multiple threads executing concurrently within the same process.

A thread is a lightweight process that can be managed independently by a scheduler. It improves the application performance using parallelism. A thread shares information like data segment, code segment, files, etc. with its peer threads while it contains its own registers, stack, counter, etc.

Locks

JavaScript doesn’t have much beyond worker threads for multithreading, but other languages commonly use locks to prevent error conditions known as race conditions from occurring when two threads share and access variables at the same time or in an order that creates unexpected results.

Deadlocks can also happen where a thread is waiting for a lock on shared data that another thread holds, but the second thread is waiting for a lock that the first thread hold.  Both threads end up never completing because they are both waiting on the other.

Four conditions must be met for a deadlock to occur:

  1. Mutual Exclusive:  Only one thread can access a resource at a given time.
  2. Hold and wait: Threads are allowed to hold a resource and then request additional resources without letting go of their current resource
  3. No Preemption: No thread can forcibly take another’s resource
  4. Circular Wait: Two or more threads form a circular loop waiting for another resource

A common way to get rid of deadlocks is to make sure you always request resources in a particular order first A, then B, then C… That way a thread can’t get A and another thread get C because the process with C would first need to wait to get A (since by the previous convention A must be acquired first).

How JavaScript Single Thread Works

Below is a video describing how JavaScript can handle asynchronous callbacks

Worker Threads

Now that you know some of the problems that can occur with either blocking the call stack or flooding the event queue, here is a new feature in JavaScript that allows you to free up the main thread by creating new worker threads.