5

Is there a portable standard-compliant way to create an std::chrono::time_point for 1 Jan 1970 00:00:00? This has to be thread-safe. Therefore, the solution should avoid functions like std::gmtime() and std::localtime() which do not have thread-safety guarantees.

This is not a duplicate of Convert std::chrono::time_point to unix timestamp since I'm asking for a portable solution that is thread-safe. Neither does the question there ask for that, nor do the answers provide this guarantee.

Community
  • 1
  • 1
Ralph Tandetzky
  • 22,780
  • 11
  • 73
  • 120
  • 1
    This sounds like two questions, 1) how to create a specific time point - no thread issues, 2) how to get the current time - potential thread issues. – wally Nov 04 '16 at 11:53
  • 1
    Possible duplicate of [Convert std::chrono::time\_point to unix timestamp](http://stackoverflow.com/questions/14504870/convert-stdchronotime-point-to-unix-timestamp) – Captain Giraffe Nov 04 '16 at 12:01
  • Beware. The Posix standard does not define "the epoch", and then rely on the normal meaning of "seconds" and "since". It defines the complete phrase "seconds since the epoch", and it doesn't mean quite you might have thought it meant. – Martin Bonner supports Monica Nov 04 '16 at 12:06
  • @CaptainGiraffe This is not a duplicate, since I'm asking for a portable and thread-safe solution. The question there does not ask for this and the answers do not provide these guarantees. – Ralph Tandetzky Nov 04 '16 at 12:10
  • AFAIK, gmtime and localtime is thread-safe in MSVC – Danh Nov 04 '16 at 12:11
  • 1
    If I can get this: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0355r1.html standardized, then a default constructed `std::chrono::time_point{}` will portably represent 1970-01-01 00:00:00 UTC. It will be thread-safe and lightning fast (requiring storing a 64 bit zero). – Howard Hinnant Nov 04 '16 at 13:55
  • @HowardHinnant It would be awesome to have something standardized that can be used safely. Especially printing a `time_point` to an `ostream` without calling thread-unsafe functions from C antiquity would be very helpful. Also extracting the date and time components from a `time_point` would help a lot. – Ralph Tandetzky Nov 07 '16 at 12:39

1 Answers1

8

In practise, std::chrono::system_clock::from_time_t(0) will return the value you want.

In principle, I can't see how to exactly what you want.

As an alternative, calculate this value once (at startup) before multiple threads have started running.