Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Downloads
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Calendar
  - Forums
  - IRC
  - Community Discord
  - Wiki
  - GitHub
  - Issues
  - Get involved
  - Contributors
  - Foundation
  - Security Team
  - Donate
  - Sponsors
- Resources
  - Tour
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - run.dlang.io
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

# core.sync.semaphore

The semaphore module provides a general use semaphore for synchronization.
License:
Boost License 1.0
Authors:
Sean Kelly

Source core/sync/semaphore.d

class `Semaphore`;
  This class represents a general counting semaphore as concieved by Edsger Dijkstra. As per Mesa type monitors however, "signal" has been replaced with "notify" to indicate that control is not transferred to the waiter when a notification is sent.
  Examples:

      import core.thread, core.atomic;

      void testWait()
      {
          auto semaphore = new Semaphore;
          shared bool stopConsumption = false;
          immutable numToProduce = 20;
          immutable numConsumers = 10;
          shared size_t numConsumed;
          shared size_t numComplete;

          void consumer()
          {
              while (true)
              {
                  semaphore.wait();

                  if (atomicLoad(stopConsumption))
                      break;
                  atomicOp!"+="(numConsumed, 1);
              }
              atomicOp!"+="(numComplete, 1);
          }

          void producer()
          {
              assert(!semaphore.tryWait());

              foreach (_; 0 .. numToProduce)
                  semaphore.notify();

              // wait until all items are consumed
              while (atomicLoad(numConsumed) != numToProduce)
                  Thread.yield();

              // mark consumption as finished
              atomicStore(stopConsumption, true);

              // wake all consumers
              foreach (_; 0 .. numConsumers)
                  semaphore.notify();

              // wait until all consumers completed
              while (atomicLoad(numComplete) != numConsumers)
                  Thread.yield();

              assert(!semaphore.tryWait());
              semaphore.notify();
              assert(semaphore.tryWait());
              assert(!semaphore.tryWait());
          }

          auto group = new ThreadGroup;

          for ( int i = 0; i < numConsumers; ++i )
              group.create(&consumer);
          group.create(&producer);
          group.joinAll();
      }

      void testWaitTimeout()
      {
          auto sem = new Semaphore;
          shared bool semReady;
          bool alertedOne, alertedTwo;

          void waiter()
          {
              while (!atomicLoad(semReady))
                  Thread.yield();
              alertedOne = sem.wait(dur!"msecs"(1));
              alertedTwo = sem.wait(dur!"msecs"(1));
              assert(alertedOne && !alertedTwo);
          }

          auto thread = new Thread(&waiter);
          thread.start();

          sem.notify();
          atomicStore(semReady, true);
          thread.join();
          assert(alertedOne && !alertedTwo);
      }

      testWait();
      testWaitTimeout();

  this(uint `count` = 0);
    Initializes a semaphore object with the specified initial count.
    Parameters:

    uint `count` | The initial count for the semaphore.

    Throws:
    SyncError on error.
  void `wait`();
    Wait until the current count is above zero, then atomically decrement the count by one and return.
    Throws:
    SyncError on error.
  bool `wait`(Duration `period`);
    Suspends the calling thread until the current count moves above zero or until the supplied time period has elapsed. If the count moves above zero in this interval, then atomically decrement the count by one and return true. Otherwise, return false.
    Parameters:

    Duration `period` | The time to wait.

    In period must be non-negative.

    Throws:
    SyncError on error.
    Returns:
    true if notified before the timeout and false if not.
  void `notify`();
    Atomically increment the current count by one. This will notify one waiter, if there are any in the queue.
    Throws:
    SyncError on error.
  bool `tryWait`();
    If the current count is equal to zero, return. Otherwise, atomically decrement the count by one and return true.
    Throws:
    SyncError on error.
    Returns:
    true if the count was above zero and false if not.
  protected alias `Handle` = core.sys.posix.semaphore.sem_t;
    Aliases the operating-system-specific semaphore type.
  protected Handle `m_hndl`;
    Handle to the system-specific semaphore.

Copyright © 1999-2022 by the D Language Foundation | Page generated by Ddoc on Thu Dec 15 17:30:05 2022