Boost logo

Boost :

From: Marcus Blomenkamp (Marcus.Blomenkamp_at_[hidden])
Date: 2002-05-25 06:50:51

Loïc Joly wrote:

> I want to run some calculations at 100Hz, those calculations
> take between 1ms and 5ms, if I just want to put a sleep after
> my calculations are done, I do not know how long it should wait
> (between 9ms and 5ms), unless I measure how long my calculations
> actually were, which I find a tedious task.

> [...]

> timed_mutex mutex (0.01); // frequency 100Hz
> timed_mutex::lock lock(mutex);
> while (true)
> {
> lock.lock();
> doMyCalculations();
> }
> I would like to have your feedback about this idea.

Hi there.
I don't think this is a good idea. First of all 'lock.lock()' will IMHO
throw an exception if it can't acquire the mutex after the expired time.
So there is extra logic to add. Second your interval will be roughly
0.01 + T(doMyCalculations) -> 105..109ms which is not as exact as it
could be.

A better idea would be to use a two-thread conecpt. One thread does
nothing but signalling a condition every 10ms and the other threads just
  repeatedly waits for the condition to be signalled. This will
definitively improve the interval precision and looks nicer/clearer IMHO.

Rough draft:

[shared variables]
mutex mtx;
condition cond;
bool do_it;

[worker thread]
while (true)
        // acquire the mutex for this scope
        lock lk(mtx);

        // wait for 'do_it' to become true
        while (! do_it)

        // clear flag
        do_it = false;

        // work

[pinger thread]
while (true)
        // some kind of sleep function

        // acquire the mutex for this scope
        lock lk(mtx)

        // set flag
        do_it = true;

        // signal the condition to wake up partner

You'd just have to invent some sleep construct since it's IIRC not in
the c++ standard or boost. You could use a timed mutex for this. I'm new
to boost so please apologize typos or other failures...


Boost list run by bdawes at, gregod at, cpdaniel at, john at