std::notify_all_at_thread_exit
Материал из cppreference.com
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
| Заголовочный файл <condition_variable>
|
||
| void notify_all_at_thread_exit( std::condition_variable& cond, std::unique_lock<std::mutex> lk ); |
(начиная с C++11) | |
notify_all_at_thread_exit предоставляет механизм для уведомления других потоков, что данный поток полностью закончен, в том числе уничтожая все thread_local объектов. Она работает следующим образом:Original:
notify_all_at_thread_exit provides a mechanism to notify other threads that a given thread has completely finished, including destroying all thread_local objects. It operates as follows:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
- Право собственности на ранее приобретенные замок
lkпередается на внутреннюю память.Original:Ownership of the previously acquired locklkis transferred to internal storage.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Среда исполнения изменяется таким образом, что при текущем выходит нить, после деструкторы для всех объектов с Тема местные продолжительности хранения называется,
condпеременная условия уведомления как быOriginal:The execution environment is modified such that when the current thread exits, after the destructors for all objects with Тема местные продолжительности хранения are called, the condition variablecondis notified as if by:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
lk.unlock();
cond.notify_all();
Эквивалентный эффект может быть достигнут с помощью средств, предоставляемых std::promise или std::packaged_task.
Original:
An equivalent effect may be achieved with the facilities provided by std::promise or std::packaged_task.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Содержание |
[править] Notes
Вызов этой функции, если
lock.mutex() не заблокирован текущим потоком неопределенное поведение.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.
You can help to correct and verify the translation. Click here for instructions.
Вызов этой функции, если
lock.mutex() это не то же мьютекса, который используется всеми другими потоками, которые в настоящее время ждет на той же переменной условие неопределенное поведение.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.
You can help to correct and verify the translation. Click here for instructions.
Замок поставляется
lk проводится, пока поток выходит. Как только эта функция была вызвана, не более потоков могут приобрести тот же замок для того, чтобы ждать на cond. Если некоторый поток ожидает на этой переменной условия, оно не должно пытаться освободить и выкупить замок, когда он просыпается, ложно.Original:
The supplied lock
lk is held until the thread exits. Once this function has been called, no more threads may acquire the same lock in order to wait on cond. If some thread is waiting on this condition variable, it should not attempt to release and reacquire the lock when it wakes up spuriously.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
В типичных случаях использования этой функции является последней вещью, которую называют отдельные нить.
Original:
In typical use cases, this function is the last thing called by a detached thread.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Параметры
| cond | - | переменная условия уведомить в потоке выхода
Original: the condition variable to notify at thread exit The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. |
| lk | - | замок, связанный с
cond переменной состояния Original: the lock associated with the condition variable cond The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. |
[править] Возвращаемое значение
(Нет)
Original:
(none)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Пример
Этот частичный фрагмент кода показывает, как
notify_all_at_thread_exit могут быть использованы, чтобы избежать доступа к данным, что зависит от потока местных жителей в то время как поток местных жителей в процесс на грани уничтожения
Original:
This partial code fragment illustrates how
notify_all_at_thread_exit can be used to avoid accessing data that depends on thread locals while those thread locals are in the process of being destructed:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
#include <mutex> #include <thread> std::mutex m; std::condition_variable cv; bool ready = false; ComplexType result; // some arbitrary type void thread_func() { std::unique_lock<std::mutex> lk(m); // assign a value to result using thread_local data result = function_that_uses_thread_locals(); ready = true; std::notify_all_at_thread_exit(cv, std::move(lk)); } // 1. destroy thread_locals, 2. unlock mutex, 3. notify cv int main() { std::thread t(thread_func); t.detach(); // do other work // ... // wait for the detached thread std::unique_lock<std::mutex> lk(m); while(!ready) { cv.wait(lk); } process(result); // result is ready and thread_local destructors have finished }
[править] См. также
| устанавливает результат определенное значение при доставке уведомлений только при выходе потока Original: sets the result to specific value while delivering the notification only at thread exit The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::promise)
| |
| выполняет функцию обеспечения того, чтобы результат готов только один раз текущий поток существует Original: executes the function ensuring that the result is ready only once the current thread exits The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::packaged_task)
| |