假设我有两个变量:
volatile int a = 0;
int b = 0;
Run Code Online (Sandbox Code Playgroud)
它们在两个线程之间共享。现在在第一个线程中,我按以下顺序修改这些变量:
a = 1;
b = 2;
Run Code Online (Sandbox Code Playgroud)
在第二个线程我做:
while (true) {
if (b == 2)
assert(a == 1);
}
Run Code Online (Sandbox Code Playgroud)
是否保证第二个线程永远不会失败?这意味着第二个线程读取出的写入的值a
,并b
以相同的顺序,他们是由第一个线程写的?
如您所见,我制作了a
volatile 和b
non-volatile。所以我的问题是 volatile 修饰符是否对内存写入的顺序有任何保证?如果我b
也制作volatile
它会改善情况吗?
或者,只有这样,才能保证顺序是使用std::atomic<int>
两个a
及b
?
怎么样std::mutex
?如果我通过两个线程上的单个共享互斥锁保护两个变量并使用非易失性变量,它是否有助于内存排序?也就是说,如果我做下一个(包括a
和b
是非易失性的):
int a = 0, b = 0; // shared
std::mutex m; // shared
// .... In Thread 1 ....
{ …
Run Code Online (Sandbox Code Playgroud) import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class Main implements Runnable {
private final CountDownLatch cdl1 = new CountDownLatch(NUM_THREADS);
private volatile int bar = 0;
private AtomicInteger count = new AtomicInteger(0);
private static final int NUM_THREADS = 25;
public static void main(String[] args) {
Main main = new Main();
for(int i = 0; i < NUM_THREADS; i++)
new Thread(main).start();
}
public void run() {
int i = count.incrementAndGet();
cdl1.countDown();
try {
cdl1.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
bar = i; …
Run Code Online (Sandbox Code Playgroud) 由于许多误解,我从头开始重新阐述了这个问题。提问的初衷没有改变。许多评论仍然引用旧的问题文本。
有关文档volatile
指出,它确保其他线程以一致的方式看到内存更新。然而,volatile
很少使用。
据我所知,synchronized
块的目的是使线程不同时执行这些关键部分。是否也会synchronized
像其他线程一样导致一致的内存更新volatile
?
这是我的简单类,它在单独的线程中递增共享变量:
public class Main {
private volatile int count;
public static void main(String[] args) {
Main main = new Main();
main.doJob();
}
private void doJob() {
Runnable runnable1 = () -> {
for (int i = 0; i < 10000; i++) {
incrementCount();
}
};
Runnable runnable2 = () -> {
for (int i = 0; i < 10000; i++) {
incrementCount();
}
};
Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable2);
t1.start();
t2.start();
try {
t1.join();
t2.join(); …
Run Code Online (Sandbox Code Playgroud) 我需要点击一个I2C设备,我在维基百科上遇到了这个代码.
#define I2CSPEED 100
void I2C_delay(void) {
volatile int v;
int i;
for (i = 0; i < I2CSPEED / 2; ++i) {
v;
}
}
Run Code Online (Sandbox Code Playgroud)
我很困惑
v;
Run Code Online (Sandbox Code Playgroud)
确实.这延迟多久了?