lundi 5 juin 2023

C++ Multithreading Callback Timer Function Thread Safety

Suppose I have implemented a callback timer class. The class takes the following arguments:

  • a timeout interval
  • a function to run

At the end of each timeout period the class spawns a thread and passes it the function to run. The function is not guaranteed to be thread safe.

Further suppose that the timeout interval is shorter than the time it takes the function to finish executing. In this case I would want the "request" to run the callback function to be "queued" so that it runs after the first invocation completes. I do not want two threads to be executing that same function concurrently.

How could I do this using std C++11 supported concurrency libraries?

...Another caveat, what if two timer instantiations are passed the same function?

Aucun commentaire:

Enregistrer un commentaire