伪共享问题

伪共享(False Sharing)是指在多线程环境中,多个线程操作不同但共享同一缓存行的数据,导致不必要的缓存一致性流量,从而降低系统性能。理解和解决伪共享问题对于优化多线程程序的性能非常重要。

缓存行和伪共享的基础知识

现代处理器使用缓存来提高内存访问速度,缓存以固定大小的块(称为缓存行,通常为64字节)存储数据。处理器在访问内存时,会将整行数据加载到缓存中。

伪共享的具体表现

当多个线程操作位于同一缓存行中的不同变量时,即使这些变量彼此独立,处理器也必须在每次写操作后进行缓存一致性维护。这会导致缓存行在不同处理器核之间频繁传输,严重影响性能。

举例说明

考虑以下示例,其中两个线程分别操作两个位于同一缓存行中的变量:

public class FalseSharingExample {
    private static class SharedData {
        public volatile long a;
        public volatile long b;
    }

    public static void main(String[] args) throws InterruptedException {
        SharedData data = new SharedData();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                data.a++;
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                data.b++;
            }
        });

        long start = System.nanoTime();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        long end = System.nanoTime();

        System.out.println("Duration: " + (end - start) / 1_000_000 + " ms");
    }
}

在这个例子中,线程1和线程2分别操作变量ab,由于这两个变量可能在同一个缓存行中,伪共享问题会导致性能下降。

解决伪共享问题

1. 通过填充变量来避免伪共享

在变量之间插入填充物,使它们占用不同的缓存行:

public class FalseSharingSolution {
    private static class PaddedData {
        public volatile long a;
        private long p1, p2, p3, p4, p5, p6, p7; // 填充物
        public volatile long b;
    }

    public static void main(String[] args) throws InterruptedException {
        PaddedData data = new PaddedData();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                data.a++;
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                data.b++;
            }
        });

        long start = System.nanoTime();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        long end = System.nanoTime();

        System.out.println("Duration: " + (end - start) / 1_000_000 + " ms");
    }
}
2. 使用 @Contended 注解

@Contended 注解是 JDK 提供的一种工具,用于避免伪共享。它通过在变量之间插入填充物来确保每个变量占用不同的缓存行。需要启用 JVM 参数 -XX:-RestrictContended

import sun.misc.Contended;

public class ContendedExample {
    @Contended
    public static class SharedData {
        public volatile long a;
        public volatile long b;
    }

    public static void main(String[] args) throws InterruptedException {
        SharedData data = new SharedData();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                data.a++;
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                data.b++;
            }
        });

        long start = System.nanoTime();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        long end = System.nanoTime();

        System.out.println("Duration: " + (end - start) / 1_000_000 + " ms");
    }
}

运行时需要加上 JVM 参数:

java -XX:-RestrictContended ContendedExample

总结

伪共享问题会导致多线程程序的性能显著下降,解决方法包括通过填充变量或使用 @Contended 注解来避免不同线程操作的变量共享同一缓存行。理解和解决伪共享问题对于优化多线程程序性能至关重要。

  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
伪共享(False Sharing)是指多个线程同时访问不同但位于同一缓存行的变量时,由于缓存一致性协议的限制,会导致缓存行多次在不同的 CPU 之间进行传递,从而降低了程序的性能。 举一个简单的例子:假设两个线程同时访问同一缓存行中的不同变量,如下所示: ``` struct CacheLine { int x; int y; } cacheLine; // 线程 1 void thread1() { while (true) { cacheLine.x++; } } // 线程 2 void thread2() { while (true) { cacheLine.y++; } } ``` 在这个例子中,由于 `x` 和 `y` 位于同一缓存行中,所以在多个线程同时访问它们时,会导致缓存行多次在不同的 CPU 之间进行传递,从而降低了程序的性能。 为了避免伪共享,可以采用以下两种方法: 1. 添加填充:为了让不同的变量位于不同的缓存行中,可以在变量之间添加一些填充,从而让它们位于不同的缓存行中,如下所示: ``` struct CacheLine { int x; char padding[60]; // 填充 int y; } cacheLine; ``` 2. 使用 `std::atomic`:使用 `std::atomic` 可以确保多线程对变量的访问是原子的,从而避免了伪共享问题,如下所示: ``` struct CacheLine { std::atomic<int> x; std::atomic<int> y; } cacheLine; ``` 以上两种方法都可以有效地避免伪共享问题,提高程序的性能。但是,需要注意的是,添加填充会增加内存的消耗,而使用 `std::atomic` 会增加程序的开销。因此,需要根据具体的场景选择合适的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值