Espacios de nombres
Variantes
Acciones

std::condition_variable

De cppreference.com
 
 
Biblioteca de apoyo de concurrencia
Hilos
(C++11)
(C++20)
Espacio de nombres this_thread
(C++11)
(C++11)
(C++11)
Cancelación cooperativa
Exclusión mutua
(C++11)
Gestión genérica de bloqueo
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Variables de condición
condition_variable
(C++11)
(C++11)
Semáforos
Pestillos y barreras
(C++20)
(C++20)
Futuros
(C++11)
(C++11)
(C++11)
(C++11)
Recuperación segura
(C++26)
Punteros de riesgo
Tipos atómicos
(C++11)
(C++20)
Inicialización de tipos atómicos
(C++11)(en desuso en C++20)
(C++11)(en desuso en C++20)
Orden de memoria
Funciones independientes para operaciones atómicas
Funciones independientes para indicadores atómicos
 
 
Definido en el archivo de encabezado <condition_variable>
class condition_variable;
(desde C++11)
La clase condition_variable es una primitiva de sincronización que se puede utilizar para bloquear un hilo, o hilos de múltiples al mismo tiempo, hasta que:
Original:
The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • se recibe una notificación de otro hilo
    Original:
    a notification is received from another thread
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • un tiempo de espera, o
    Original:
    a timeout expires, or
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • un activación espuria se produce
    Original:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Cualquier hilo que tiene la intención de esperar en std::condition_variable tiene que adquirir un std::unique_lock primero. Las operaciones de espera atómicamente liberar la exclusión mutua y la suspensión de la ejecución de la rosca. Cuando la variable de estado se notifica, el hilo se despertó y volvió a adquirir el mutex está .
Original:
Any thread that intends to wait on std::condition_variable has to acquire a std::unique_lock first. The wait operations atomically release the mutex and suspend the execution of the thread. When the condition variable is notified, the thread is awakened, and the mutex is reacquired.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
La clase es un std::condition_variable StandardLayoutType. No es CopyConstructible, MoveConstructible, CopyAssignable, MoveAssignable .
Original:
The class std::condition_variable is a StandardLayoutType. It is not CopyConstructible, MoveConstructible, CopyAssignable, MoveAssignable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Contenido

Tipos de miembros

Miembro de tipo
Original:
Member type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Definition
native_handle_type
' Definido por la implantación
Original:
implementation-defined
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Las funciones miembro

Construye el objeto.
(función miembro pública) [editar]
Destruye el objeto.
(función miembro pública) [editar]
operator=
[eliminada]
No es asignable mediante copia.
(función miembro pública) [editar]
Notificación
Original:
Notification
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Notifica a un hilo en espera.
(función miembro pública) [editar]
Notifica a todos los hilos en espera.
(función miembro pública) [editar]
Espera
Original:
Waiting
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Bloquea el hilo actual hasta que la variable de condición se despierte.
(función miembro pública) [editar]
Bloquea el hilo actual hasta que la variable de condición se despierte o hasta después del tiempo de espera especificado.
(función miembro pública) [editar]
Bloquea el hilo actual hasta que la variable de condición se despierte o se haya alcanzado el punto de tiempo especificado.
(función miembro pública) [editar]
Identificador nativo
Original:
Native handle
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Devuelve el identificador nativo.
(función miembro pública) [editar]

Ejemplo

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
 
int main()
{
    std::queue<int> produced_nums;
    std::mutex m;
    std::condition_variable cond_var;
    bool done = false;
    bool notified = false;
 
    std::thread producer([&]() {
        for (int i = 0; i < 5; ++i) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::unique_lock<std::mutex> lock(m);
            std::cout << "producing " << i << '\n';
            produced_nums.push(i);
            notified = true;
            cond_var.notify_one();
        }   
 
        done = true;
        cond_var.notify_one();
    }); 
 
    std::thread consumer([&]() {
        std::unique_lock<std::mutex> lock(m);
        while (!done) {
            while (!notified) {  // loop to avoid spurious wakeups
                cond_var.wait(lock);
            }   
            while (!produced_nums.empty()) {
                std::cout << "consuming " << produced_nums.front() << '\n';
                produced_nums.pop();
            }   
            notified = false;
        }   
    }); 
 
    producer.join();
    consumer.join();
}

Posible salida:

producing 0
consuming 0
producing 1
consuming 1
producing 2
consuming 2
producing 3
consuming 3
producing 4
consuming 4