Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
1 KB
Referenced Files
None
Subscribers
None
diff --git a/util/timer.cpp b/util/timer.cpp
new file mode 100644
index 00000000..4da516cb
--- /dev/null
+++ b/util/timer.cpp
@@ -0,0 +1,41 @@
+#include "timer.h"
+#include "init.h"
+#include "funcs.h"
+
+namespace Util{
+
+void * do_wait(void * timer_){
+ Timer * timer = (Timer *) timer_;
+ unsigned int now = Global::second_counter;
+ /* add 1 because the current time is in between X and X+1 */
+ while (Global::second_counter - now < timer->wait+1){
+ Util::rest(50);
+ bool do_stop = false;
+ pthread_mutex_lock(&timer->lock);
+ do_stop = timer->stopped;
+ pthread_mutex_unlock(&timer->lock);
+ if (do_stop){
+ return NULL;
+ }
+ }
+ timer->func(timer->arg);
+ return NULL;
+}
+
+Timer::Timer(unsigned int seconds_to_wait, timeout func, void * arg):
+wait(seconds_to_wait),
+func(func),
+arg(arg),
+stopped(false){
+ pthread_mutex_init(&lock, NULL);
+ pthread_create(&timer, NULL, do_wait, this);
+}
+
+void Timer::stop(){
+ pthread_mutex_lock(&lock);
+ stopped = true;
+ pthread_mutex_unlock(&lock);
+ pthread_join(timer, NULL);
+}
+
+}
diff --git a/util/timer.h b/util/timer.h
new file mode 100644
index 00000000..8c9618f8
--- /dev/null
+++ b/util/timer.h
@@ -0,0 +1,29 @@
+#ifndef _paintown_util_timer_h
+#define _paintown_util_timer_h
+
+#include <pthread.h>
+
+namespace Util{
+
+/* calls a function after X seconds unless stop() is called first */
+class Timer{
+public:
+ typedef void (*timeout)(void * arg);
+ Timer(unsigned int seconds_to_wait, timeout func, void * arg);
+
+ void stop();
+
+ friend void * do_wait(void * timer_);
+
+protected:
+ unsigned int wait;
+ timeout func;
+ void * arg;
+ bool stopped;
+ pthread_mutex_t lock;
+ pthread_t timer;
+};
+
+}
+
+#endif

File Metadata

Mime Type
text/x-diff
Expires
Thu, Jun 11, 1:29 PM (3 w, 4 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
69251
Default Alt Text
(1 KB)

Event Timeline