• Post Reply Bookmark Topic Watch Topic
  • New Topic

mutex on multiple cpus

 
jason williams
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22519
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
jason williams
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!