Bassam Badr
Bassam Badr

Reputation: 667

mutual exclusion using thread of java

I have this code , It is mutual exclusion algorithm

turn = 0 // shared control variable    

while (turn != i);

// CS

turn = (turn + 1) % n;

I know how thread works but really I'm little weak in using thread in java so please any suggestion to help me to understand how to convert it in real code using thread of java

sorry for my bad english

Upvotes: 0

Views: 12217

Answers (2)

shaydel
shaydel

Reputation: 589

this code is not mutually exclusive, consider this execution-

  1. thread 0 enters the code and CS and then increments turn to 1 in the last line.
  2. thread 1 enters the CS as turn equals 1,and stays
  3. now thread 0 goes back to the first line and sets turn to 0 and then enters the CS together with thread 1

Upvotes: 0

EdH
EdH

Reputation: 5003

Mutual exclusion is typically achieved, in the simplest form, by marking a method as synchronized. By marking an object's method as synchronized, only one thread can ever execute that object's method at a time. The object owning the method is the monitor.

Additionally, you can define a synchronized block in the code itself, passing it the object to act as the monitor.

I believe you could achieve the same thing in a simpler fashion, by defining a Runnable object which has the logic you want done. Where you want the mutual exclusion, define a synchronized method.

Then that Runnable instance can be passed to as many Threads you need. As they all reference the same Runnable, calls into the synchronized method will be mutually exclusive.

This is not the only way, but it should be what you're after. Hope this helps.

Upvotes: 4

Related Questions