c - How locking actually works -


i got 1 question simple one. while implementing simple locking mechanism using global variable.i can't find out how prevent access of global variable 2 processes/thread.

my algorithm (take 2 process)

  • process p1 check if variable g set not modify code.
  • if not set set modify code.
  • same process 2 .

while executing got fair result correct. doubt in architecture if 2 instructions not atomic how avoid accessing global variable @ time.

please give me basic idea.

use atomic methods manipulate global variable.

atomic operations 'built-in' gcc. while not 'portable', compilers offer atomic operations.

for gcc, might implement this:

if(__sync_bool_compare_and_swap(&g, g, g+1))    /* changed you. */; else    /* process changed before could. perhaps try again. */ 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -