我这样实现 Time Thread 是否可行?

2022-04-30 17:45:16 +08:00
 guang19

某个场景是需要频繁的调用系统时间,但是精度要求不那么高(误差在 500ms - 800ms 左右吧)。网上有人提出 TimeThread 的设计即单起一个后台线程维护一个时间变量,用的时候直接获取这个时间变量就可以了。我不太确定这种方案的可行性,于是自己尝试实现了下,下面是大致实现:

.h

		class TimeThread
		{
			private:
				TimeThread();
				~TimeThread();

			public:
				inline ::std::time_t getCurrentTime() const
				{
					return currentTime_;
				}

			private:
				void updateCurrentTime();

			private:
				::std::atomic<bool> running_ { false };
				::std::time_t currentTime_ { 0 };
				::std::thread timeThread_ {};
		};

.cpp

		namespace
		{
			constexpr uint32_t MicrosecondsPerSecond = 1000000U;
			struct timeval tmV {};
		}

		TimeThread::TimeThread() : running_(true)
		{
			::gettimeofday(&tmV, nullptr);
			currentTime_ = (tmV.tv_sec * MicrosecondsPerSecond) + tmV.tv_usec;
			timeThread_ = ::std::thread(&TimeThread::updateCurrentTime, this);
		}

		TimeThread::~TimeThread()
		{
			running_ = false;
			if (timeThread_.joinable())
			{
				timeThread_.join();
			}
		}

		void TimeThread::updateCurrentTime()
		{
			while (running_)
			{
				::gettimeofday(&tmV, nullptr);
				currentTime_ = (tmV.tv_sec * MicrosecondsPerSecond) + tmV.tv_usec;
				::std::this_thread::sleep_for(::std::chrono::milliseconds(50));
			}
		}

还有我把这个类作为单例供其他需要的模块使用是否可行? 求各位大牛帮忙指出方案和代码的缺陷,感谢!

1274 次点击
所在节点    程序员
2 条回复
cppc
2022-04-30 20:38:50 +08:00
稳妥期间,可以在 loop 里检查一下上一次保存的时间和当前时间差了多少,偏离过大起码也得记录个日志之类
guang19
2022-04-30 23:21:16 +08:00
@cppc 好的,感谢。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/850232

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX