| Author |
mutex on multiple cpus
|
jason williams
Greenhorn
Joined: Nov 17, 2004
Posts: 14
|
|
I am learning mutex lately. So I wrote programs for practicing this issue on multiple cpus. However, it seems there is a problem for my code but I am not aware of where goes wrong.
Code are as below:
Result shows
The value obtained by thread 0 and 1 are the same, which seems incorrect.
Does which parts of the code go wrong? Or is there any tutorial or resource with actual code telling how to write mutex on multiple cpu or smp?
Thanks for help.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
Although, your code has "Lock" and "Mutex" as names, there are no locks or mutexes anywhere to be seen.
In order to implement a mutex, you need to have the lock() and unlock() methods be completely atomic -- which yours are not. And to do that, you have a few options...
You can use synchronization -- which itself can be considered a mutex... so no need to implement one yourself.
You can use the atomic classes (located in java.util.concurrent.atomic package) which can make your methods behave atomically. Although admittedly, this is not for the faint of heart, as optimistic locking is an advanced topic.
Or you can use the lock classes (located in java.util.concurrent.locks) which implements mutexes, reader-writer locks, semaphores, etc. And done so optimistically, and very efficiently. So, no need to implement your own mutex class.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
jason williams
Greenhorn
Joined: Nov 17, 2004
Posts: 14
|
|
Henry Wong wrote:Although, your code has "Lock" and "Mutex" as names, there are no locks or mutexes anywhere to be seen.
In order to implement a mutex, you need to have the lock() and unlock() methods be completely atomic -- which yours are not. And to do that, you have a few options...
You can use synchronization -- which itself can be considered a mutex... so no need to implement one yourself.
You can use the atomic classes (located in java.util.concurrent.atomic package) which can make your methods behave atomically. Although admittedly, this is not for the faint of heart, as optimistic locking is an advanced topic.
Or you can use the lock classes (located in java.util.concurrent.locks) which implements mutexes, reader-writer locks, semaphores, etc. And done so optimistically, and very efficiently. So, no need to implement your own mutex class.
Henry
Sorry the code is not listed completely.
My impl of Mutex is as below. And these code are just for practise for myself to have better understanding on how mutex works.
Thanks for help.
|
 |
 |
|
|
subject: mutex on multiple cpus
|
|
|