zoukankan      html  css  js  c++  java
  • 线程同步之mutex和Semaphore

    表示之前对semaphore信号量木有神码概念。

    比较纳闷这玩意要干嘛,好吧继续stackflow:

    Mutex can be released only by thread that had acquired it, while you can signal semaphore from any other thread (or process), so semaphores are more suitable for some synchronization problems like producer-consumer.

    意思就是会所semaphore可以被任何线程或者进程释放,在生产者和消费者模型里用的比较多;

    而mutex只能被拥有它的线程被释放,但如果这个线程突然当掉了,操作系统会负责释放它。

    On Windows, binary semaphores are more like event objects than mutexes.

    另一个拿分的解释是:

    Mutex:

    Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.

    Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library

    (A mutex is really a semaphore with value 1.)

    mutex是厕所钥匙,一次只能一人那着这把钥匙去厕所。结束了,这个人把钥匙给队列中的下一个人。

    Semaphore:

    Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

    信号量是一个自由的官方厕所钥匙,我们有四个厕所,他们的锁和钥匙是一样的。信号量开始设置为4,表示4个厕所是自由滴,如果一个人进去了,数量就-1.如果厕所满了,钥匙数目就为0,信号量数目这时也是0.如果一个人离开厕所,信号量+!,队列中的下一个人可以用啦!

    Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library

    信号量限制一份资源的最大同步个数。线程可以请求进入资源,并在用完资源时发出信号。

  • 相关阅读:
    010 排序: 冒泡 选择
    洛谷 P1540 机器翻译
    洛谷 P1011 车站
    周期串
    2019.03.29 大数据图解
    2019.03.29 算法解读
    2019.03.28 博客反省
    2019.03.27 常用的模块
    2019.03.25 git
    2019.03.25 Ajax三级联动
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/3305609.html
Copyright © 2011-2022 走看看