Boost thread and try_join_for each time give different results

Suppose I have the following code:

#include <boost/chrono.hpp>
#include <boost/thread.hpp>

#include <iostream>

int main()
{
  boost::thread thd([]{ std::cout << "str \n"; });

  boost::this_thread::sleep_for(boost::chrono::seconds(3));

  if (thd.try_join_for(boost::chrono::nanoseconds(1)))
  {
    std::cout << "Finished \n";
  }
  else
  {
    std::cout << "Running \n";
  }
}

MSVC-12.0 and boost 1.55 give me a different output every time I run this program. For instance,

str
Finished

str
Finished

str
Running

When I change boost :: chrono :: nanoseconds to increase :: chrono :: microseconds, the result looks as expected.

Why? What am I doing wrong? Is this a bug in the accelerator library? Is there a ticket about what happens in the error tracking alarm clock?

Thanks in advance.

+4
source share
2 answers

Your program simply has a race, most likely due to the fact that 1 nanosecond is terribly short.

try_join_for try_join_until, , , :

// I stripped some unrelated template stuff from the code
//  to make it more readable

bool try_join_for(const chrono::duration& rel_time)
{
  return try_join_until(chrono::steady_clock::now() + rel_time);
}

bool try_join_until(const chrono::time_point& t)
{
  system_clock::time_point     s_now = system_clock::now();
  bool joined= false;
  do {
    Clock::duration   d = ceil<nanoseconds>(t-Clock::now());
    if (d <= Clock::duration::zero())
        return false; // in case the Clock::time_point t is already reached
    // only here we attempt to join for the first time:
    joined = try_join_until(s_now + d);
  } while (! joined);
  return true;
}

, try_join_until , . , clock::now() , , . , 1 , .

, . - , CPU , . , .

+3

.join()? , , :

#include <boost/chrono.hpp>
#include <boost/thread.hpp>

#include <iostream>

int main()
{
  boost::thread thd([]{ std::cout << "str\n"; });
  boost::this_thread::sleep_for(boost::chrono::seconds(3));

  if (thd.joinable())
      thd.join();
}

, Undefined , .

  • ,

, , .

0

Source: https://habr.com/ru/post/1535955/


All Articles