Reputation: 12535
In some cases we need to be sure that some section of code won't be used by one thread while another thread is in this section. Using languages that support multi-threading it's easy to achieve with "locking" these parts. But when we have to "simulate" threads there's not built-in thing like lock
keyword in C# or Lock
interface in Java. The best way I've found to lock sections in these cases look likes this:
if (!locked){
locked = true;
do some stuff
locked = false;
} else {
add to queue
}
What are the drawbacks of current solution? Does it worth to actively use one?
Upvotes: 0
Views: 77
Reputation: 8679
Take a look at double-checked locking and syncronization primitives provided by underlaying system or OS: mutex, semaphore, motinore, etc. You'll be suprised that even C++ does not have Lock
keyword, but everything is fine. C# lock
is implemented using monitor and you could find more details here.
Upvotes: 1
Reputation: 15234
Maybe two threads can enter in the if
statement.
Explanation
If T1
entered in the if
statement and doesn't change the locked
value. Suddenly, if the CPU change T1
for T2
, locked
value will continue false
. Then T2
will enter into if
statement too.
T1 -> !locked -> Stopped -> Waiting -> ... //locked value still false and T2
T2 -> Waiting -> Waked -> !locked -> ... //will be able to enter into if
You should take a look at Semaphores and Mutexes and If you will only use two process you can use the Peterson's Algorithm, but it still have a busy wait to deal!
Upvotes: 2