Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ `Timer` class implementation

I've designed a Timer class, which dispatches (using an Observer pattern) an event each n n-seconds. Of course it creates a new thread in order not to block the thread it was called from.

Then I've thought - hmmm... let's say 100 clients connect to my server-program, I create 3 timers for each of them, so I run 300 threads. Isn't it much? Is it an ok, that I run 300 threads?

Then I was told that in AS3 Timer runs in main thread. And I wondered: HOW??? How can I implement a timer running in main thread and not blocking it? Is it possible in C++?

like image 608
Kolyunya Avatar asked Sep 13 '12 08:09

Kolyunya


1 Answers

A possible solution is to just use one thread for all timers, and have a queue ordered by the timeout. The problem with this is that when a timer expires and you call the callback function, it will run in the context of the global timer thread and not separately.This can of course be solved by spawning a new thread just for the event, which is then joined directly, or by having a thread-pool to handle the events, so the main timer thread will not be "clogged up".

like image 94
Some programmer dude Avatar answered Oct 01 '22 09:10

Some programmer dude