开发者

Java mutex with smp

开发者 https://www.devze.com 2023-01-05 23:54 出处:网络
I am learning multi-thread programming; and whilst practising mutex, I notice that it seems doesn\'t work correctly on my dule-c开发者_开发技巧ore laptop.

I am learning multi-thread programming; and whilst practising mutex, I notice that it seems doesn't work correctly on my dule-c开发者_开发技巧ore laptop.

The mutex code is at http://pastebin.com/axGY5y3c

The result is as below:

count value:t[0]1
count value:t[1]1
count value:t[2]2
count value:t[3]3
count value:t[4]4

The result shows that seemly the threads would obtain the same init value at the beginning. That looks incorrect.

Is there anything wrong with my code? Or is there any resource providing examples about running java mutex on smp/ dule-core/ multiple cpus?

Thanks for help.


I'm not very familiar with mutex algorithms, so I can't help you strictly concerning the concurrency. I did, however spot one line in your code that explains why you get the values you listed:

public class MyThread extends Thread{
    // [...]
    private static int count = 0;

When you start four threads, run() is called four times, incrementing count each iteration.

This block of code:

t[i].start();
int v = t[i].getCountValue();
System.out.println("count value:t["+i+"]"+v;

Therefore is effectively:

count++;
System.out.println("count value:t["+i+"]"+count);


As Paul has mentioned, you have the confusion that "count" is declared as static, but then when you retrieve it, you're implying you don't want it to be static. Fundamentally, you need to decide what you want the program to do.

But... in any case, there are other issues:

  • in your implementation, you're accessing data structures shared across threads (each thread may have its own array element, but the actual array reference is shared across threads); according to the Java Memory Model, you need to take steps to make this safe (e.g. declaring the arrays final or volatile, or using an atomic array);
  • there are standard concurrency libraries that may actually perform better in practice (or at least be correct and more flexible), though of course as an academic exercise understanding concurrent algorithms isn't a bad thing.


I think I roughly know the problem of my code. The printed line in Test.java contains the function getCountValue(), which is not in the boundary of lock (mutex.lock()/ mutex.unlock()); therefore when thread starts to print the count value, resulting in race condition because printing the value of count needs not to wait for other thread.

After moving the getCountValue() inside the run() function, which is inside the boundary of lock. The result looks correct. It prints out

pid:0 count value:1
pid:2 count value:2
pid:3 count value:3
pid:1 count value:4
pid:4 count value:5

Thanks again for all your help. I appreciate it.

0

精彩评论

暂无评论...
验证码 换一张
取 消