-2

When two processors hit the request of getting access to a variable simultabeiusly, which one will get the access to the variable. On upper level i.e. programming level, we simply call the mutex to get access of the variable, but how does os handle it on hardware level.

  • 1
    possible duplicate of [How are mutexes implemented?](http://stackoverflow.com/questions/1485924/how-are-mutexes-implemented) – Boann Dec 27 '14 at 08:38
  • hi sir, thanks for the link. but in given link "When CPU 1 issues a test-and-set instruction, the DPRAM first makes an "internal note" of this by storing the address of the memory location in a special place. If at this point, CPU 2 happens to issue a test-and-set instruction for the same memory location, the DPRAM first checks its "internal note", recognizes the situation, and issues a BUSY interrupt, which tells CPU 2 that it must wait and retry. " what if both cpu try to access simultaneously? – user2098173 Dec 27 '14 at 17:38

1 Answers1

0

pthread_mutex_lock and pthread_mutex_trylock are implemented as an atomic operation.

http://en.cppreference.com/w/cpp/concept/Mutex (for c++) http://en.wikipedia.org/wiki/Mutual_exclusion

This can be implemented on the hardware level or the software level. If two threads try the same operation at the same time, it guaranteed that one will succeed, the other will fail. Lock requests are queued as a FIFO. Last thread added to the queue wins. If there are incoming requests (at precisely the same time) the queue processes them ALL randomly and the last one in gets the mutex ( assuming it is available).

See source code here: http://code.google.com/p/pthread-lib/source/browse/trunk/pthread-lib/src/ptl_array_list.c

jim mcnamara
  • 16,005
  • 2
  • 34
  • 51