
Semaphore(信号量)是一种并发控制工具,用于限制同时访问特定资源的线程数量。它本身并非线程安全性的保证者,而是控制“门禁”。当Semaphore的许可数等于1时,它充当互斥锁,确保独占访问。然而,当许可数大于1时,多个线程可以同时进入受保护的代码块,此时,被访问的共享资源本身的线程安全性就变得至关重要,可能需要额外的同步机制来避免竞态条件。
Semaphore在并发编程中扮演着“许可管理器”的角色,其核心作用是控制对共享资源的并发访问量。你可以将其想象成一个停车场,Semaphore的许可数就是停车位的数量。当一个线程想要访问资源时,它需要先“获取”一个许可;当它完成访问后,需要“释放”这个许可。如果所有许可都被占用,其他线程就必须等待,直到有许可被释放。
需要明确的是,Semaphore本身是一个线程安全的类,它内部管理许可计数的操作是原子性的。然而,Semaphore的职责仅限于管理并发访问的数量,它并不能直接赋予被保护的资源以线程安全性。资源的线程安全性需要单独考虑。
当Semaphore的初始化许可数(permits)设置为1时,它被称为二元信号量(Binary Semaphore),其行为类似于一个互斥锁(Mutex)。在这种模式下,任何时刻都只允许一个线程成功获取许可并进入由Semaphore保护的临界区。
例如,以下Java代码展示了一个二元信号量的使用:
import java.util.concurrent.Semaphore;
public class BinarySemaphoreExample {
private final Semaphore semaphore = new Semaphore(1); // 许可数为1
private int sharedCounter = 0; // 非线程安全的共享资源
public void increment() throws InterruptedException {
semaphore.acquire(); // 获取许可
try {
// 此时,只有一个线程能进入此代码块
sharedCounter++;
System.out.println(Thread.currentThread().getName() + " incremented counter to: " + sharedCounter);
} finally {
semaphore.release(); // 释放许可
}
}
public static void main(String[] args) {
BinarySemaphoreExample example = new BinarySemaphoreExample();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
try {
example.increment();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "Thread-" + i).start();
}
}
}在这个例子中,尽管 sharedCounter 本身是非线程安全的,但由于 semaphore 保证了 increment() 方法内部的 sharedCounter++ 操作在任何时候都只被一个线程执行,因此不会发生竞态条件,数据能够保持一致性。
当Semaphore的许可数大于1时(例如 permits = 2),它允许多个(最多等于许可数的)线程同时获取许可并进入由Semaphore保护的临界区。这是Semaphore与互斥锁最显著的区别。
在这种情况下,Semaphore的作用是限制并发线程的“数量上限”,但它并不能阻止这些并发线程之间对共享资源进行不安全的访问。如果被保护的共享资源本身不是线程安全的,那么即使在Semaphore允许的并发数量内,仍然可能出现数据不一致、竞态条件等问题。
例如,如果我们将上述 BinarySemaphoreExample 中的许可数改为2:
import java.util.concurrent.Semaphore;
public class MultiPermitSemaphoreExample {
private final Semaphore semaphore = new Semaphore(2); // 许可数为2
private int sharedCounter = 0; // 非线程安全的共享资源
public void increment() throws InterruptedException {
semaphore.acquire(); // 获取许可
try {
// 此时,可能有两个线程同时在此代码块内
// sharedCounter++ 操作不再是原子性的,可能导致竞态条件
sharedCounter++; // !!! 潜在的线程不安全操作
System.out.println(Thread.currentThread().getName() + " incremented counter to: " + sharedCounter);
} finally {
semaphore.release(); // 释放许可
}
}
public static void main(String[] args) {
MultiPermitSemaphoreExample example = new MultiPermitSemaphoreExample();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
try {
example.increment();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "Thread-" + i).start();
}
}
}在这个修改后的例子中,semaphore 允许两个线程同时执行 increment() 方法。当两个线程同时读取 sharedCounter 的旧值,然后分别对其进行递增并写回时,最终 sharedCounter 的值可能低于预期。例如,如果 sharedCounter 当前为0,两个线程同时读取到0,然后都递增为1并写回,最终 sharedCounter 仍然是1,而不是预期的2。这就是典型的竞态条件。
要解决多许可Semaphore下共享资源的线程安全问题,我们需要结合其他同步机制:
使用线程安全的资源: 如果被Semaphore保护的资源本身就是线程安全的,那么 permits > 1 的Semaphore可以直接用于限制对该资源的整体并发访问量,而无需额外的内部同步。例如,使用 java.util.concurrent.atomic 包中的原子类(如 AtomicInteger)或 java.util.concurrent 包中的并发集合(如 ConcurrentHashMap)。
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeMultiPermitSemaphoreExample {
private final Semaphore semaphore = new Semaphore(2);
private final AtomicInteger sharedCounter = new AtomicInteger(0); // 线程安全的共享资源
public void increment() throws InterruptedException {
semaphore.acquire();
try {
// AtomicInteger的incrementAndGet()方法是原子性的
int newValue = sharedCounter.incrementAndGet();
System.out.println(Thread.currentThread().getName() + " incremented counter to: " + newValue);
} finally {
semaphore.release();
}
}
// ... main 方法类似 ...
}在这个例子中,即使两个线程同时进入 try 块,AtomicInteger 的 incrementAndGet() 方法也能保证操作的原子性,从而避免竞态条件。
在临界区内进行额外同步: 如果被保护的资源是非线程安全的,并且你选择使用多许可Semaphore,那么在每个线程获取Semaphore许可后,进入临界区内部操作非线程安全资源时,还需要使用 synchronized 块、ReentrantLock 等机制进行更细粒度的同步。
import java.util.concurrent.Semaphore;
public class NestedSynchronizationExample {
private final Semaphore semaphore = new Semaphore(2); // 允许两个线程并发
private int sharedCounter = 0; // 非线程安全的共享资源
private final Object lock = new Object(); // 用于保护sharedCounter的内部锁
public void increment() throws InterruptedException {
semaphore.acquire(); // 获取Semaphore许可
try {
// 此时,可能有两个线程同时在此代码块内
// 但对sharedCounter的修改被内部的synchronized块保护
synchronized (lock) { // 额外使用一个内部锁来保护非线程安全操作
sharedCounter++;
System.out.println(Thread.currentThread().getName() + " incremented counter to: " + sharedCounter);
}
} finally {
semaphore.release(); // 释放Semaphore许可
}
}
// ... main 方法类似 ...
}在这个例子中,Semaphore控制了最多两个线程可以同时“进入房间”,但进入房间后,如果他们需要操作同一个“不安全的工具”(sharedCounter),他们还需要排队使用这个工具,这就是 synchronized (lock) 的作用。
理解Semaphore的工作原理以及它与资源线程安全之间的关系,是编写健壮、高效并发程序的关键。正确地结合使用不同的同步工具,才能有效管理并发,避免潜在的线程安全问题。
以上就是Semaphore与线程安全:多许可下如何保障资源同步的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号