Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How locks are implemented on multiple cores

For a uni-processor, the lock algorithm is pretty simple.

Lock(threadID) {
  Disable Interrupts
  If lock is already owned by same thread{
    Restore Interrupts
    return
  }
  if lock is free {
    make lock busy
    set current thread as the owner of the lock
  }
  else {
     add threadID to the lock queue.
  }
  Restore Interrupts
  return
}

But how do we implement this code in multiprocessor/multicore systems. What if 2 cores/procs try to give the same lock to different processes.

like image 356
user447851 Avatar asked Apr 22 '11 21:04

user447851


People also ask

How are locks implemented?

Locks have two operations: acquire allows a thread to take ownership of a lock. If a thread tries to acquire a lock currently owned by another thread, it blocks until the other thread releases the lock. At that point, it will contend with any other threads that are trying to acquire the lock.

How do multiple CPU cores work?

A multicore processor is an integrated circuit that has two or more processor cores attached for enhanced performance and reduced power consumption. These processors also enable more efficient simultaneous processing of multiple tasks, such as with parallel processing and multithreading.

How do multiple cores communicate?

Currently, the core-to-core communication is performed by sending and receiving software commands between cores. Therefore, the processor needs to allocate a considerable part of its computational resources to executing these software commands.

What is the purpose of locks in multiprocessor systems?

On a multiprocessor system, simple locks, which protect thread-interrupt critical sections, must be used in conjunction with interrupt control in order to serialize execution both within the executing processor and between different processors.


1 Answers

Mutexes are generally implemented with atomic operations on a single memory value. For instance, a lock can be a single word that is free when 0 and locked when 1. To acquire the lock, the processor will lock the memory bus (so no other processors can read or write to memory), read the most-current value of the word, set it to 1 if it is 0, and unlock the memory bus. To unlock, the word can be set to 0.

That's a simple example that doesn't address what happens when the lock is contended. Different OSs handle that using different mechanisms. Linux uses something called futexes. I'm not sure what Windows or Macs do.

Although the algorithm you posted is correct, non-kernel code can't disable CPU interrupts, so user-space code will tend to use atomic operations even on a single core.

like image 170
Karmastan Avatar answered Nov 03 '22 08:11

Karmastan