Reputation: 260
I'm fairly new to Real Time programming/multithreading and I'm trying to get some practical development under my belt. I'm trying to code a program (in C) for a school project that performs several tasks, including image processing (openCV), serving webpages (with a library like libmicrohttpd), and interfacing with a peripheral. This program will be heavily threaded, with each task basically running independently.
A very central part of this program is event/data logging and setting the clock on a peripheral, which requires the computer's onboard time. That is to say, more than one of the threads will require the current time as part of its task. So my question is, is it a better idea to declare a global time struct and call gettime as it's needed in individual threads, or to have a separate thread that always maintains the current time, which every thread then just reads from? The former sounds like it could have access issues, while the second sounds challenging to update at the proper frequency.
To give a more detailed idea of the tasks that I'm doing:
Thanks for any advice.
Upvotes: 2
Views: 203
Reputation: 21
You said that your device have no RTC. So I expect it is a small embedded platform? If so, there is almost always some ware a hardware timer available. If so you can use an interrupt or use a tread to poll the timer value. And don't forget to log the time adjustments so you can evaluate them later on.
Upvotes: 0
Reputation: 46309
Your best option is to use a threadsafe time getter. gettimeofday
is one such function (see here: Is the gettimeofday function thread safe in Linux?). It gives you seconds and microseconds since the unix epoch, so should easily be accurate enough for logging. What you do with the data you get out of that function is up to you, as long as you don't use any functions which have internal buffers, etc.
You should also be careful about how you write your logs. The safest way is to use separate files for each thread, but you can use mutex locks as well.
Upvotes: 3