tags:

views:

41

answers:

2

I have 2 functions.

void fn1() and void fn2(). Both the functions are using the same data say int i; Both the functions are executed simultaneously by 2 different processes. Then how should the variable i be protected such that 1 function should not be allowed to change i until the other changes something like locking the variable i and then unlocking it.

I need some simple example of how locking and unlocking of i is done(not using built API's of semaphore etc)

A: 

you can use a global variable say int LOCK which is set as 1 as soon as some function tries accessing the variable i. The variable will be set to 0 when the LOCK is released.

and in your function void fn1() and void fn2() put in a if-else loop which goes in execution only when lock is not set. and when it goes in the loop it updates the global variable and releases it when it comes out of loop.

Egalitarian
A: 

See, for example, this algorithm. Or this one.

zvrba