发生在线程和原子变量之间的第2部分 [英] Happens before between threads and atomic variable Part 2

查看:78
本文介绍了发生在线程和原子变量之间的第2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于回答在线程和原子变量之间发生之前是断言不成立,因此我需要一个替代方法执行.线程1和线程2分别更新整数t1和t2.一旦更新,则不会对t1或t2进行其他任何更新.分配给t1和t2的值来自一个公共计数器,该计数器在每次分配后都会递增.我需要确保以下断言是正确的;

Since answer to Happens before between threads and atomic variable was that the asserts don't hold, I need an alternate implementation. Thread1 and Thread2 each update Integers t1 and t2 respectively. Once they are updated no other updates occur to t1 or t2. The values assigned to t1 and t2 come from a common counter which gets incremented after each assignment. I need to ensure the following asserts are true;

int cnt=0;
ReentrantLock lock = new ReentrantLock();
volatile Integer t1=null;
volatile Integer t2=null;

//Thread1
lock.lock();
try{t1=cnt++;}finally{lock.unlock();}
if(t2 == null){
  assert t2==null || t2>t1;
}

//Thread2
lock.lock();
try{t2=cnt++;}finally{lock.unlock();}
if(t1==null){
  assert t1==null || t1>t2;
}

问题是断言是否成立?如图所示,t1和t2上是否需要挥发物?有没有更好/正确的方法来实现这一目标?

The question is do the asserts hold? Is volatile required on t1 and t2 as shown? Is there a better/correct way to accomplish this?

推荐答案

  1. 是的,断言会过去.每次读取和写入之间都有HB,并且可以确保如果第一个线程获得锁定,则第二个线程既不能递增计数器,也不能初始化其t变量.因此,如果线程在if(t1==null){} t2内部,则它将是null或更大的值,然后是t1.另一个线程也是如此.
  2. 您无法从该代码中删除volatile,因为t1t2在不同线程之间共享,并且您需要确保在不同线程中该字段的读取和写入之间存在HB.
  3. 如果存在更好的解决方案,恐怕我找不到这么快的解决方案.我认为任何可能进入if(t1==null){...}的正确解决方案都必须满足要求:t1=cnt++必须仅由一个线程同时执行.
  1. Yes, asserts will pass. There is HB between every read and write and there is guarantee that if the first thread get lock, the second one can neither nor increment the counter, nor initialize it's t variable. Therefore if a thread is inside if(t1==null){} t2 will be null or greater then t1. The same is true for another thread.
  2. You can not remove volatile from that code because t1 and t2 are shared between different threads and you need to ensure there is HB between reads and writes of that fields in different threads.
  3. If better solution exists, I am afraid that I am not able to find it so fast. I think any correct solution where it is possible to go inside if(t1==null){...} must meet the requirement: t1=cnt++ must be being performed by only one thread simultaneously.

这篇关于发生在线程和原子变量之间的第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆