All streams
Search
Write a publication
Pull to refresh
7
0
Send message

Решаем проблемы с RAII у std::thread: cancellation_token как альтернатива pthread_cancel и boost::thread::interrupt

Reading time10 min
Views17K

Статья рассматривает проблемы в std::thread, попутно разрешая древний спор на тему "что использовать: pthread_cancel, булев флаг или boost::thread::interrupt?"


Проблема


У класса std::thread, который добавили в C++11, есть одна неприятная особенность — он не соответствует идиоме RAII (Resource Acquisition Is Initialization). Выдержка из стандарта:


30.3.1.3 thread destructor
~thread();
If joinable() then terminate(), otherwise no effects.

Чем нам грозит такой деструктор? Программист должен быть очень аккуратен, когда речь идёт об разрушении объекта std::thread:


void dangerous_thread()
{
  std::thread t([] { do_something(); });
  do_another_thing(); // may throw - can cause termination!
  t.join();
}

Читать дальше →

Information

Rating
Does not participate
Registered
Activity