1

I would like to create a new thread that remains in a loop. Something like this:

void Clock() {
    double Time = 0;
    while (1) {
        usleep(1000);
        Time = (Time+0.1);
    }
    return;
}

I would then like my other existing threads to be able to access the latest clock value and use it. How do I declare the "Time" variable so that it can be accessed by all threads and how would I alter the code above to accommodate that? And also what would i need to do to access it?

Giovanni Funchal
  • 8,934
  • 13
  • 61
  • 110
Mst137
  • 133
  • 9
  • 1
    Make it a global variable? – Some programmer dude Aug 25 '16 at 14:29
  • @JoachimPileborg I have many different source files, can i declare a global variable in a header file to ensure its able to be used in all of my source files? or is there a different solution – Mst137 Aug 25 '16 at 14:31
  • Just making it a global variable would be begging for a race condition. Make it a static with an accessor function that locks a mutex. Lock the same mutex in your `Clock()` function (just while updating, not while sleeping!). – Fred Larson Aug 25 '16 at 14:32
  • 5
    You realize that time is going to drift? – 2501 Aug 25 '16 at 14:32
  • 2
    Just use a POSIX timer. – EOF Aug 25 '16 at 14:34
  • @FredLarson: I would not recommend using a mutex. That way, reading the clock in another thread can greatly increase clock-drift. I'd *at least* use a lock-free atomic. But obviously using a proper timer would be preferable anyway. – EOF Aug 25 '16 at 14:35
  • 1
    @EOF: That's great. Just as long as the race condition is prevented somehow. And yes, this isn't a wheel that should be reinvented. – Fred Larson Aug 25 '16 at 14:38
  • You either need atomic types or use a mutex. – David Schwartz Aug 25 '16 at 17:22

1 Answers1

1

If you just want to obtain the current time, you can do so without a thread. Have a look at Get the current time in C for example.

If you use a thread, please be aware that threads run independently. Have a look at Mutex lock threads for a simple example. You will need to use pthread_create to create the thread, and pthread_mutex to protect the Time variable.

I would recommend you start with that first, and leave atomics to the next time.

Community
  • 1
  • 1
Giovanni Funchal
  • 8,934
  • 13
  • 61
  • 110