public member function
<condition_variable>

std::condition_variable_any::notify_one

void notify_one() noexcept;
Notify one
Unblocks one of the threads currently waiting for this condition.

If no threads are waiting, the function does nothing.

If more than one, it is unspecified which of the threads is selected.

Parameters

none

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// condition_variable_any::notify_one
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex
#include <condition_variable> // std::condition_variable_any

std::mutex mtx;
std::condition_variable_any cv;

int cargo = 0;     // shared value by producers and consumers

void consumer () {
  mtx.lock();
  while (cargo==0) cv.wait(mtx);
  std::cout << cargo << '\n';
  cargo=0;
  mtx.unlock();
}

void producer (int id) {
  mtx.lock();
  cargo = id;
  cv.notify_one();
  mtx.unlock();
}

int main ()
{
  std::thread consumers[10],producers[10];

  // spawn 10 consumers and 10 producers:
  for (int i=0; i<10; ++i) {
    consumers[i] = std::thread(consumer);
    producers[i] = std::thread(producer,i+1);
  }

  // join them back:
  for (int i=0; i<10; ++i) {
    producers[i].join();
    consumers[i].join();
  }

  return 0;
}


Possible output (order of consumed cargoes may vary):

1
2
3
4
5
6
7
8
9
10

Data races

No data races (atomic operation).
Atomic operations on the object are ordered according to a single total order.

Exception safety

No-throw guarantee: never throws exceptions.

See also