semaphore

一文看懂 Mutex vs Semaphore vs Monitor vs SemaphoreSlim

安稳与你 提交于 2019-12-02 23:08:09
C#开发者(面试者)都会遇到Mutex,Semaphore,Monitor,SemaphoreSlim这四个与锁相关的C#类型,本文期望以最简洁明了的方式阐述四种对象的区别。 什么叫线程安全? 教条式理解 如果代码在多线程环境中运行的结果与 单线程运行结果一样,其他变量值也和预期是一样的,那么线程就是安全的; 线程不安全就是不提供数据访问保护,可能出现多个线程先后修改数据造成的结果是脏数据。 实际场景理解 两个线程都为集合增加元素,我们错误的理解即使是多线程也总有先后顺序吧,集合的两个位置先后塞进去就完了;实际上集合增加元素这个行为看起来简单,实际并不一定是原子操作。 在添加一个元素的时候,它可能会有两步来完成: 在 Items[Size] 的位置存放此元素; 增大 Size 的值。 在单线程运行的情况下,如果 Size = 0,添加一个元素后,此元素在位置0,之后设置Size=1; 如果是在多线程场景下,有两个线程,线程A先将元素存放在位置0,但是此时CPU调度线程A暂停,线程B得到运行机会;线程B也向此ArrayList添加元素,因为此时Size仍然等于0 (注意哦,我们假设添加元素是经过两个步骤,而线程A仅仅完成了步骤1),所以线程B也将元素存放在位置0。然后线程A和线程B都继续运行,都增加 Size 的值。 那好,我们来看看ArrayList的情况,元素实际上只有一个

Semaphore

旧街凉风 提交于 2019-12-02 22:59:14
public class Semaphore implements java.io.Serializable { private static final long serialVersionUID = -3222578661600680210L; /** All mechanics via AbstractQueuedSynchronizer subclass */ private final Sync sync; /** * 继承AQS以实现信号量机制,使用AQS的state属性代表允许使用的信号量的数量,该Sync类有两个 * 派生类,其中一个是公平模式的,另一个是非公平模式的 */ abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1192457210091910933L; Sync(int permits) { setState(permits); } final int getPermits() { return getState(); } //非公平模式的获取信号量 final int nonfairTryAcquireShared(int acquires) { for (;;) { int

python3 信号量semaphore

匿名 (未验证) 提交于 2019-12-02 22:51:08
提前设定好,一个房间只有4个床(计数器现在为4),那么同时只能四个人进来,谁先来的谁先占一个床(acquire,计数器减1),4个床满了之后(计数器为0了),第五个人就要等着,等其中一个人出来(release,计数器加1),他就去占用那个床了。 互斥锁同时只允许一个线程更改数据,而信号量 Semaphore 是同时允许一定数量的线程更改数据 。 假设商场里有 4 个迷你唱吧,所以同时可以进去 4 个人,如果来了第五个人就要在外面等待,等到有人出来才能再进去玩。 实现: 信号量同步基于内部计数器,每调用一次 acquire (),计数器减 1 ;每调用一次 release (),计数器加 1. 当计数器为 0 时, acquire ()调用被阻塞。这是迪科斯彻( Dijkstra )信号量概念 P ()和 V ()的 Python 实现。信号量同步机制适用于访问像服务器这样的有限资源。 信号量与进程池的概念很像,但是要区分开,信号量涉及到加锁的概念 # coding:utf-8 import time import random from multiprocessing import Process , Semaphore def go_ktv ( i , sem ): print ( "user%s马上要进>>>>>ktv." % i ) sem . acquire ()

Java并发编程:CountDownLatch、CyclicBarrier和Semaphore

匿名 (未验证) 提交于 2019-12-02 21:53:32
Java并发编程:CountDownLatch、CyclicBarrier和Semaphore   在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch,CyclicBarrier和Semaphore,今天我们就来学习一下这三个辅助类的用法。   以下是本文目录大纲:   一.CountDownLatch用法   二.CyclicBarrier用法   三.Semaphore用法   若有不正之处请多多谅解,并欢迎批评指正。   请尊重作者劳动成果,转载请标明原文链接:   http://www.cnblogs.com/dolphin0520/p/3920397.html    一.CountDownLatch用法   CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。   CountDownLatch类只提供了一个构造器: 1 public CountDownLatch( int //参数count为计数值 1 2 3 public void throws //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行 public

[******] java多线程连续打印abc

匿名 (未验证) 提交于 2019-12-02 21:52:03
题目描述 建立三个线程A、B、C,A线程打印10次字母A,B线程打印10次字母B,C线程打印10次字母C,但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印。 5种方法 使用synchronized, wait和notifyAll 使用Lock->ReentrantLock 和 state标志 使用Lock->ReentrantLock 和Condition(await 、signal、signalAll) 使用Semaphore 使用AtomicInteger 扩展:采用join实现(一次性打印) 5.1 使用synchronized, wait和notifyAll public class ABC7 { private static Object o = new Object();//所对象 private static int state = 0;//控制顺序 private static int PRINT_NUMBER = 10;//打印次数 private static int THREAD_NUM = 3;//线程数量 static class ThreadGenetic implements Runnable { char name; int data; public ThreadGenetic(char name, int data){

What is the Mutex and semaphore In c#? where we need to implement? [closed]

三世轮回 提交于 2019-12-02 20:35:07
What is the Mutex and semaphore in C#? Where we need to implement? How can we work with them in multithreading? You should start at MSDN. System.Threading.Mutex : A synchronization primitive that can also be used for interprocess synchronization. System.Threading.Semaphore : Limits the number of threads that can access a resource or pool of resources concurrently. Generally you only use a Mutex across processes, e.g. if you have a resource that multiple applications must share, or if you want to build a single-instanced app (i.e. only allow 1 copy to be running at one time). A semaphore allows

H2O 生成

僤鯓⒐⒋嵵緔 提交于 2019-12-02 19:44:32
现在有两种线程,氢 oxygen 和氧 hydrogen,你的目标是组织这两种线程来产生水分子。 存在一个屏障(barrier)使得每个线程必须等候直到一个完整水分子能够被产生出来。 氢和氧线程会被分别给予 releaseHydrogen 和 releaseOxygen 方法来允许它们突破屏障。 这些线程应该三三成组突破屏障并能立即组合产生一个水分子。 你必须保证产生一个水分子所需线程的结合必须发生在下一个水分子产生之前。 换句话说: 如果一个氧线程到达屏障时没有氢线程到达,它必须等候直到两个氢线程到达。 如果一个氢线程到达屏障时没有其它线程到达,它必须等候直到一个氧线程和另一个氢线程到达。 书写满足这些限制条件的氢、氧线程同步代码。 示例 1: 输入: "HOH" 输出: "HHO" 解释: "HOH" 和 "OHH" 依然都是有效解。 示例 2: 输入: "OOHHHH" 输出: "HHOHHO" 解释: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" 和 "OHHOHH" 依然都是有效解。 限制条件: 输入字符串的总长将会是 3n, 1 ≤ n ≤ 50; 输入字符串中的 “H” 总数将会是 2n; 输入字符串中的 “O” 总数将会是 n。 在真实的面试中遇到过这道题? 链接:https

When to use Semaphore instead of Dispatch Group?

帅比萌擦擦* 提交于 2019-12-02 17:45:09
I would assume that I am aware of how to work with DispatchGroup , for understanding the issue, I've tried: class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() performUsingGroup() } func performUsingGroup() { let dq1 = DispatchQueue.global(qos: .userInitiated) let dq2 = DispatchQueue.global(qos: .userInitiated) let group = DispatchGroup() group.enter() dq1.async { for i in 1...3 { print("\(#function) DispatchQueue 1: \(i)") } group.leave() } group.wait() dq2.async { for i in 1...3 { print("\(#function) DispatchQueue 2: \(i)") } } group.notify(queue:

Monitor vs Mutex

会有一股神秘感。 提交于 2019-12-02 17:32:15
I read that mutex is a semaphore with value 1 (binary semaphore) which is used for enforcing mutual exclusion. I read this link Semaphore vs. Monitors - what's the difference? which says that monitor helps in achieving mutual exclusion. Can anyone tell me the difference between mutex and monitor as both are actually doing the same thing Since you haven't specified which OS or language/library you are talking about, let me answer in a generic way. Conceptually they are the same. But usually they are implemented slightly differently Monitor Usually, the implementation of monitors is faster/light

Counting distinct words with Threads

天大地大妈咪最大 提交于 2019-12-02 15:10:06
问题 The objective is to count distinct words from a file. UPDATE: Previous Code was successfully finished. Now I have to do the same but using threads (Oh man, I hate them...) and in addition I want to make it with semaphores for better flow. Code contains some extra stuff left out from previous attempts, I'm trying to figure out what can be used.. I can read one word at a time but mostly I get a "null" in the container. So until I get anything from the container all the time I can't test the