◐ Shell
clean mode source ↗

std::condition_variable::wait_for - cppreference.com

De cppreference.com

<metanoindex/>

<tbody> </tbody>

template< class Rep, class Period > std::cv_status wait_for( std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time);

(1) (desde C++11)

template< class Rep, class Period, class Predicate > bool wait_for( std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time, Predicate pred);

(2) (desde C++11)

1)

Atomicamente libera lock, bloqueia a thread atual em execução, e acrescenta-lo à lista de espera da thread em *this. A discussão será desbloqueado quando notify_all() ou notify_one() é executado, ou quando o tempo limite rel_time relativa expirar. Também pode ser desbloqueado spuriously. Quando desbloqueado, independentemente do motivo, lock é readquirido e sai wait_for(). Se esta função saídas via de exceção, lock também é readquirida.

Original:

Atomically releases lock, blocks the current executing thread, and adds it to the list of threads waiting on *this. The thread will be unblocked when notify_all() or notify_one() is executed, or when the relative timeout rel_time expires. It may also be unblocked spuriously. When unblocked, regardless of the reason, lock is reacquired and wait_for() exits. If this function exits via exception, lock is also reacquired.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

2)

Equivalente a

Original:

Equivalent to

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

while (!pred()) if (wait_for(lock, rel_time) == std::cv_status::timeout) return pred(); return true;

Essa sobrecarga pode ser usada para ignorar despertares espúrios.

Original:

This overload may be used to ignore spurious awakenings.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Parâmetros

lock -

um objeto de std::unique_lock<std::mutex> tipo, que deve ser bloqueado pelo thread atual

Original:

an object of type std::unique_lock<std::mutex>, which must be locked by the current thread

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

rel_time -

um objeto de std::chrono::duration tipo que representa o tempo máximo de espera para gastar

Original:

an object of type std::chrono::duration representing the maximum time to spend waiting

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

pred - predicate which returns ​false

se o tempo de espera deve ser continuado

Original:

if the waiting should be continued

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

.

The signature of the predicate function should be equivalent to the following:

bool pred();

Valor de retorno

1)

std::cv_status::timeout se o tempo limite relativo especificado pelo rel_time expirado, std::cv_status::no_timeout overwise.

Original:

std::cv_status::timeout if the relative timeout specified by rel_time expired, std::cv_status::no_timeout overwise.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

2)

false se o predicado pred ainda avalia a false após o tempo limite expirou rel_time, caso contrário true.

Original:

false if the predicate pred still evaluates to false after the rel_time timeout expired, otherwise true.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Exceções

Pode lançar std::system_error, também podem propagar exceções lançadas por lock.lock() ou lock.unlock().

Original:

May throw std::system_error, may also propagate exceptions thrown by lock.lock() or lock.unlock().

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Notas

Chamar essa função se lock.mutex() não está bloqueada pelo atual segmento é um comportamento indefinido.

Original:

Calling this function if lock.mutex() is not locked by the current thread is undefined behavior.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Chamar essa função se lock.mutex() não é o mesmo mutex como o utilizado por todos os outros segmentos que estão aguardando na variável mesma condição é um comportamento indefinido.

Original:

Calling this function if lock.mutex() is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Exemplo

#include <iostream>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <chrono>

std::condition_variable cv;
std::mutex cv_m;
std::atomic<int> i = ATOMIC_VAR_INIT(0);

void waits(int idx)
{
    std::unique_lock<std::mutex> lk(cv_m);
    if(cv.wait_for(lk, std::chrono::milliseconds(idx*100), [](){return i == 1;})) 
        std::cerr << "Thread " << idx << " finished waiting. i == " << i << '\n';
    else
        std::cerr << "Thread " << idx << " timed out. i == " << i << '\n';
}

void signals()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(120));
    std::cerr << "Notifying...\n";
    cv.notify_all();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    i = 1;
    std::cerr << "Notifying again...\n";
    cv.notify_all();
}

int main()
{
    std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals);
    t1.join(); t2.join(), t3.join(), t4.join();
}

Saída:

Thread 1 timed out. i == 0
Notifying...
Thread 2 timed out. i == 0
Notifying again...
Thread 3 finished waiting. i == 1

Veja também

bloqueia o segmento atual até que a variável de condição é acordado

Original:

blocks the current thread until the condition variable is woken up

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.


(função pública membro) [edit]

bloqueia o segmento atual até que a variável de condição é acordado ou até ponto de tempo especificado foi alcançado

Original:

blocks the current thread until the condition variable is woken up or until specified time point has been reached

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.


(função pública membro) [edit]