Opened 6 years ago

#12690 new Bugs

Boost Asio race condition

Reported by: Ivan Kostov <ikostov@…> Owned by: chris_kohlhoff
Milestone: To Be Determined Component: asio
Version: Boost 1.62.0 Severity: Problem
Keywords: race condition Cc:

Description

The following test case issues an warning when executed with the thread sanitizer. The problem occurs when there is a pending job and the associated work is canceled.

BOOST_AUTO_TEST_CASE(ioServiceShallWaitForPendingJobs)
{
  auto test = []()
  {
    boost::asio::io_service service;
    std::unique_ptr<boost::asio::io_service::work> work 
      (new boost::asio::io_service::work(service));
    std::thread t(
      [&service]()
      {
        service.run();
      }
    );
    std::atomic_bool called{false};
    service.post(
        [&called]()
        {
          std::this_thread::sleep_for (std::chrono::milliseconds(50));
          called = true;
        }
    );
    std::this_thread::sleep_for (std::chrono::milliseconds(1));

    work.reset(); // -> race 
    t.join();
    BOOST_REQUIRE(called);
  };

  for( size_t i = 0 ; i < 100000; ++i)
  {
    BOOST_TEST_MESSAGE(i);
    test();
  }
}

The fix is in asio/detail/posix_event.hpp:55

  // Signal the event and unlock the mutex.
  template <typename Lock>
  void signal_and_unlock(Lock& lock)
  {
    BOOST_ASIO_ASSERT(lock.locked());
    signalled_ = true;
//    lock.unlock();
    ::pthread_cond_signal(&cond_); // Ignore EINVAL.
    lock.unlock(); // first signal and then unlock as the name implies
  }

Please find the output of the Clang as an attachment

Attachments (1)

ClangThreadSanitizer.txt (10.5 KB ) - added by Ivan Kostov <ikostov@…> 6 years ago.

Download all attachments as: .zip

Change History (1)

by Ivan Kostov <ikostov@…>, 6 years ago

Attachment: ClangThreadSanitizer.txt added
Note: See TracTickets for help on using tickets.