开发者

Threadsafe way to convert time between timezones

I am writing a application to convert utc-time to different timezones, now I can use something like this

putenv("TZ=TIMEZONE1"); 
tzset()
...
do time conversions

but I don't think it is thread safe, so is there any C/C++ library which can do timezone conversion by taking timezone as argument to fu开发者_StackOverflow社区nction instead of being some global


You probably need your own code/library capable of handling time zones. The standard library's handling is very backwards and not suitable for working with anything more complex than a single timezone that's fixed for the lifetime of the program.

One possible solution, though, would be to allocate shared memory, fork, and change the timezone in the child process, then pass the result back via shared memory to be read after waitpid returns in the parent. This is mildly expensive, but not as bad as it sounds, since fork is fast on modern systems. My experience is that 1 fork equals 2-3 pthread_create calls, and 1 pthread_create call equals 2-3 open calls. Since changing timezones will require opening one or more files and performing IO on them, you probably won't be increasing the total time cost by more than a factor of 3-5 times. If you could keep around a child process for each timezone you're working with, it could be more efficient, of course.


Boost.DateTime supports time-zone conversions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜