Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::counting_semaphore,std::binary_semaphore

      From cppreference.com
      <cpp‎ |thread
       
       
      Concurrency support library
      Threads
      (C++11)
      (C++20)
      this_thread namespace
      (C++11)
      (C++11)
      (C++11)
      Cooperative cancellation
      Mutual exclusion
      Generic lock management
      (C++11)
      (C++11)
      (C++11)
      (C++11)
      Condition variables
      (C++11)
      Semaphores
      counting_semaphorebinary_semaphore
      (C++20)(C++20)
      Latches and Barriers
      (C++20)
      (C++20)
      Futures
      (C++11)
      (C++11)
      (C++11)
      Safe reclamation
      Hazard pointers
      Atomic types
      (C++11)
      (C++20)
      Initialization of atomic types
      (C++11)(deprecated in C++20)
      (C++11)(deprecated in C++20)
      Memory ordering
      (C++11)(deprecated in C++26)
      Free functions for atomic operations
      Free functions for atomic flags
       
       
      Defined in header<semaphore>
      template<std::ptrdiff_t LeastMaxValue=/* implementation-defined */>
      class counting_semaphore;
      (1)(since C++20)
      using binary_semaphore= std::counting_semaphore<1>;
      (2)(since C++20)
      1) Acounting_semaphore is a lightweight synchronization primitive that can control access to a shared resource. Unlike astd::mutex, acounting_semaphore allows more than one concurrent access to the same resource, for at leastLeastMaxValue concurrent accessors. The program is ill-formed ifLeastMaxValue is negative.
      2)binary_semaphore is an alias for specialization ofstd::counting_semaphore withLeastMaxValue being1. Implementations may implementbinary_semaphore more efficiently than the default implementation ofstd::counting_semaphore.

      Acounting_semaphore contains an internal counter initialized by the constructor. This counter is decremented by calls toacquire() and related methods, and is incremented by calls torelease(). When the counter is zero,acquire() blocks until the counter is incremented, buttry_acquire() does not block;try_acquire_for() andtry_acquire_until() block until the counter is incremented or a timeout is reached.

      Similar tostd::condition_variable::wait(),counting_semaphore'stry_acquire() can spuriously fail.

      Specializations ofstd::counting_semaphore are notDefaultConstructible,CopyConstructible,MoveConstructible,CopyAssignable, orMoveAssignable.

      Contents

      [edit]Data Members

      Member name Definition
      counter(private) The internal counter of typestd::ptrdiff_t.
      (exposition-only member object*)

      [edit]Member functions

      constructs acounting_semaphore
      (public member function)[edit]
      destructs thecounting_semaphore
      (public member function)[edit]
      operator=
      [deleted]
      counting_semaphore is not assignable
      (public member function)[edit]
      Operations
      increments the internal counter and unblocks acquirers
      (public member function)[edit]
      decrements the internal counter or blocks until it can
      (public member function)[edit]
      tries to decrement the internal counter without blocking
      (public member function)[edit]
      tries to decrement the internal counter, blocking for up to a duration time
      (public member function)[edit]
      tries to decrement the internal counter, blocking until a point in time
      (public member function)[edit]
      Constants
      [static]
      returns the maximum possible value of the internal counter
      (public static member function)[edit]

      [edit]Notes

      As its name indicates, theLeastMaxValue is theminimum max value, not theactual max value. Thusmax() can yield a number larger thanLeastMaxValue.

      Unlikestd::mutex acounting_semaphore is not tied to threads of execution - acquiring a semaphore can occur on a different thread than releasing the semaphore, for example. All operations oncounting_semaphore can be performed concurrently and without any relation to specific threads of execution, with the exception of the destructor which cannot be performed concurrently but can be performed on a different thread.

      Semaphores are also often used for the semantics of signaling/notifying rather than mutual exclusion, by initializing the semaphore with0 and thus blocking the receiver(s) that try toacquire(), until the notifier "signals" by invokingrelease(n). In this respect semaphores can be considered alternatives tostd::condition_variables, often with better performance.

      Feature-test macroValueStdFeature
      __cpp_lib_semaphore201907L(C++20)std::counting_semaphore,std::binary_semaphore

      [edit]Example

      Run this code
      #include <chrono>#include <iostream>#include <semaphore>#include <thread> // global binary semaphore instances// object counts are set to zero// objects are in non-signaled statestd::binary_semaphore    smphSignalMainToThread{0},    smphSignalThreadToMain{0}; void ThreadProc(){// wait for a signal from the main proc// by attempting to decrement the semaphore    smphSignalMainToThread.acquire(); // this call blocks until the semaphore's count// is increased from the main proc std::cout<<"[thread] Got the signal\n";// response message // wait for 3 seconds to imitate some work// being done by the threadusingnamespace std::literals;std::this_thread::sleep_for(3s); std::cout<<"[thread] Send the signal\n";// message // signal the main proc back    smphSignalThreadToMain.release();} int main(){// create some worker threadstd::thread thrWorker(ThreadProc); std::cout<<"[main] Send the signal\n";// message // signal the worker thread to start working// by increasing the semaphore's count    smphSignalMainToThread.release(); // wait until the worker thread is done doing the work// by attempting to decrement the semaphore's count    smphSignalThreadToMain.acquire(); std::cout<<"[main] Got the signal\n";// response message    thrWorker.join();}

      Output:

      [main] Send the signal[thread] Got the signal[thread] Send the signal[main] Got the signal
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/thread/counting_semaphore&oldid=171868"

      [8]ページ先頭

      ©2009-2025 Movatter.jp