SDL_timer.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../SDL_internal.h"
  19. #include "SDL_timer.h"
  20. #include "SDL_timer_c.h"
  21. #include "SDL_atomic.h"
  22. #include "SDL_cpuinfo.h"
  23. #include "../thread/SDL_systhread.h"
  24. /* #define DEBUG_TIMERS */
  25. #if !defined(__EMSCRIPTEN__) || !SDL_THREADS_DISABLED
  26. typedef struct _SDL_Timer
  27. {
  28. int timerID;
  29. SDL_TimerCallback callback;
  30. void *param;
  31. Uint32 interval;
  32. Uint32 scheduled;
  33. SDL_atomic_t canceled;
  34. struct _SDL_Timer *next;
  35. } SDL_Timer;
  36. typedef struct _SDL_TimerMap
  37. {
  38. int timerID;
  39. SDL_Timer *timer;
  40. struct _SDL_TimerMap *next;
  41. } SDL_TimerMap;
  42. /* The timers are kept in a sorted list */
  43. typedef struct {
  44. /* Data used by the main thread */
  45. SDL_Thread *thread;
  46. SDL_atomic_t nextID;
  47. SDL_TimerMap *timermap;
  48. SDL_mutex *timermap_lock;
  49. /* Padding to separate cache lines between threads */
  50. char cache_pad[SDL_CACHELINE_SIZE];
  51. /* Data used to communicate with the timer thread */
  52. SDL_SpinLock lock;
  53. SDL_sem *sem;
  54. SDL_Timer *pending;
  55. SDL_Timer *freelist;
  56. SDL_atomic_t active;
  57. /* List of timers - this is only touched by the timer thread */
  58. SDL_Timer *timers;
  59. } SDL_TimerData;
  60. static SDL_TimerData SDL_timer_data;
  61. /* The idea here is that any thread might add a timer, but a single
  62. * thread manages the active timer queue, sorted by scheduling time.
  63. *
  64. * Timers are removed by simply setting a canceled flag
  65. */
  66. static void
  67. SDL_AddTimerInternal(SDL_TimerData *data, SDL_Timer *timer)
  68. {
  69. SDL_Timer *prev, *curr;
  70. prev = NULL;
  71. for (curr = data->timers; curr; prev = curr, curr = curr->next) {
  72. if ((Sint32)(timer->scheduled-curr->scheduled) < 0) {
  73. break;
  74. }
  75. }
  76. /* Insert the timer here! */
  77. if (prev) {
  78. prev->next = timer;
  79. } else {
  80. data->timers = timer;
  81. }
  82. timer->next = curr;
  83. }
  84. static int SDLCALL
  85. SDL_TimerThread(void *_data)
  86. {
  87. SDL_TimerData *data = (SDL_TimerData *)_data;
  88. SDL_Timer *pending;
  89. SDL_Timer *current;
  90. SDL_Timer *freelist_head = NULL;
  91. SDL_Timer *freelist_tail = NULL;
  92. Uint32 tick, now, interval, delay;
  93. /* Threaded timer loop:
  94. * 1. Queue timers added by other threads
  95. * 2. Handle any timers that should dispatch this cycle
  96. * 3. Wait until next dispatch time or new timer arrives
  97. */
  98. for ( ; ; ) {
  99. /* Pending and freelist maintenance */
  100. SDL_AtomicLock(&data->lock);
  101. {
  102. /* Get any timers ready to be queued */
  103. pending = data->pending;
  104. data->pending = NULL;
  105. /* Make any unused timer structures available */
  106. if (freelist_head) {
  107. freelist_tail->next = data->freelist;
  108. data->freelist = freelist_head;
  109. }
  110. }
  111. SDL_AtomicUnlock(&data->lock);
  112. /* Sort the pending timers into our list */
  113. while (pending) {
  114. current = pending;
  115. pending = pending->next;
  116. SDL_AddTimerInternal(data, current);
  117. }
  118. freelist_head = NULL;
  119. freelist_tail = NULL;
  120. /* Check to see if we're still running, after maintenance */
  121. if (!SDL_AtomicGet(&data->active)) {
  122. break;
  123. }
  124. /* Initial delay if there are no timers */
  125. delay = SDL_MUTEX_MAXWAIT;
  126. tick = SDL_GetTicks();
  127. /* Process all the pending timers for this tick */
  128. while (data->timers) {
  129. current = data->timers;
  130. if ((Sint32)(tick-current->scheduled) < 0) {
  131. /* Scheduled for the future, wait a bit */
  132. delay = (current->scheduled - tick);
  133. break;
  134. }
  135. /* We're going to do something with this timer */
  136. data->timers = current->next;
  137. if (SDL_AtomicGet(&current->canceled)) {
  138. interval = 0;
  139. } else {
  140. interval = current->callback(current->interval, current->param);
  141. }
  142. if (interval > 0) {
  143. /* Reschedule this timer */
  144. current->interval = interval;
  145. current->scheduled = tick + interval;
  146. SDL_AddTimerInternal(data, current);
  147. } else {
  148. if (!freelist_head) {
  149. freelist_head = current;
  150. }
  151. if (freelist_tail) {
  152. freelist_tail->next = current;
  153. }
  154. freelist_tail = current;
  155. SDL_AtomicSet(&current->canceled, 1);
  156. }
  157. }
  158. /* Adjust the delay based on processing time */
  159. now = SDL_GetTicks();
  160. interval = (now - tick);
  161. if (interval > delay) {
  162. delay = 0;
  163. } else {
  164. delay -= interval;
  165. }
  166. /* Note that each time a timer is added, this will return
  167. immediately, but we process the timers added all at once.
  168. That's okay, it just means we run through the loop a few
  169. extra times.
  170. */
  171. SDL_SemWaitTimeout(data->sem, delay);
  172. }
  173. return 0;
  174. }
  175. int
  176. SDL_TimerInit(void)
  177. {
  178. SDL_TimerData *data = &SDL_timer_data;
  179. if (!SDL_AtomicGet(&data->active)) {
  180. const char *name = "SDLTimer";
  181. data->timermap_lock = SDL_CreateMutex();
  182. if (!data->timermap_lock) {
  183. return -1;
  184. }
  185. data->sem = SDL_CreateSemaphore(0);
  186. if (!data->sem) {
  187. SDL_DestroyMutex(data->timermap_lock);
  188. return -1;
  189. }
  190. SDL_AtomicSet(&data->active, 1);
  191. /* Timer threads use a callback into the app, so we can't set a limited stack size here. */
  192. data->thread = SDL_CreateThreadInternal(SDL_TimerThread, name, 0, data);
  193. if (!data->thread) {
  194. SDL_TimerQuit();
  195. return -1;
  196. }
  197. SDL_AtomicSet(&data->nextID, 1);
  198. }
  199. return 0;
  200. }
  201. void
  202. SDL_TimerQuit(void)
  203. {
  204. SDL_TimerData *data = &SDL_timer_data;
  205. SDL_Timer *timer;
  206. SDL_TimerMap *entry;
  207. if (SDL_AtomicCAS(&data->active, 1, 0)) { /* active? Move to inactive. */
  208. /* Shutdown the timer thread */
  209. if (data->thread) {
  210. SDL_SemPost(data->sem);
  211. SDL_WaitThread(data->thread, NULL);
  212. data->thread = NULL;
  213. }
  214. SDL_DestroySemaphore(data->sem);
  215. data->sem = NULL;
  216. /* Clean up the timer entries */
  217. while (data->timers) {
  218. timer = data->timers;
  219. data->timers = timer->next;
  220. SDL_free(timer);
  221. }
  222. while (data->freelist) {
  223. timer = data->freelist;
  224. data->freelist = timer->next;
  225. SDL_free(timer);
  226. }
  227. while (data->timermap) {
  228. entry = data->timermap;
  229. data->timermap = entry->next;
  230. SDL_free(entry);
  231. }
  232. SDL_DestroyMutex(data->timermap_lock);
  233. data->timermap_lock = NULL;
  234. }
  235. }
  236. SDL_TimerID
  237. SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param)
  238. {
  239. SDL_TimerData *data = &SDL_timer_data;
  240. SDL_Timer *timer;
  241. SDL_TimerMap *entry;
  242. SDL_AtomicLock(&data->lock);
  243. if (!SDL_AtomicGet(&data->active)) {
  244. if (SDL_TimerInit() < 0) {
  245. SDL_AtomicUnlock(&data->lock);
  246. return 0;
  247. }
  248. }
  249. timer = data->freelist;
  250. if (timer) {
  251. data->freelist = timer->next;
  252. }
  253. SDL_AtomicUnlock(&data->lock);
  254. if (timer) {
  255. SDL_RemoveTimer(timer->timerID);
  256. } else {
  257. timer = (SDL_Timer *)SDL_malloc(sizeof(*timer));
  258. if (!timer) {
  259. SDL_OutOfMemory();
  260. return 0;
  261. }
  262. }
  263. timer->timerID = SDL_AtomicIncRef(&data->nextID);
  264. timer->callback = callback;
  265. timer->param = param;
  266. timer->interval = interval;
  267. timer->scheduled = SDL_GetTicks() + interval;
  268. SDL_AtomicSet(&timer->canceled, 0);
  269. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  270. if (!entry) {
  271. SDL_free(timer);
  272. SDL_OutOfMemory();
  273. return 0;
  274. }
  275. entry->timer = timer;
  276. entry->timerID = timer->timerID;
  277. SDL_LockMutex(data->timermap_lock);
  278. entry->next = data->timermap;
  279. data->timermap = entry;
  280. SDL_UnlockMutex(data->timermap_lock);
  281. /* Add the timer to the pending list for the timer thread */
  282. SDL_AtomicLock(&data->lock);
  283. timer->next = data->pending;
  284. data->pending = timer;
  285. SDL_AtomicUnlock(&data->lock);
  286. /* Wake up the timer thread if necessary */
  287. SDL_SemPost(data->sem);
  288. return entry->timerID;
  289. }
  290. SDL_bool
  291. SDL_RemoveTimer(SDL_TimerID id)
  292. {
  293. SDL_TimerData *data = &SDL_timer_data;
  294. SDL_TimerMap *prev, *entry;
  295. SDL_bool canceled = SDL_FALSE;
  296. /* Find the timer */
  297. SDL_LockMutex(data->timermap_lock);
  298. prev = NULL;
  299. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  300. if (entry->timerID == id) {
  301. if (prev) {
  302. prev->next = entry->next;
  303. } else {
  304. data->timermap = entry->next;
  305. }
  306. break;
  307. }
  308. }
  309. SDL_UnlockMutex(data->timermap_lock);
  310. if (entry) {
  311. if (!SDL_AtomicGet(&entry->timer->canceled)) {
  312. SDL_AtomicSet(&entry->timer->canceled, 1);
  313. canceled = SDL_TRUE;
  314. }
  315. SDL_free(entry);
  316. }
  317. return canceled;
  318. }
  319. #else
  320. #include <emscripten/emscripten.h>
  321. typedef struct _SDL_TimerMap
  322. {
  323. int timerID;
  324. int timeoutID;
  325. struct _SDL_TimerMap *next;
  326. } SDL_TimerMap;
  327. typedef struct {
  328. int nextID;
  329. SDL_TimerMap *timermap;
  330. } SDL_TimerData;
  331. static SDL_TimerData SDL_timer_data;
  332. static void
  333. SDL_Emscripten_TimerHelper(SDL_TimerMap *entry, Uint32 interval, SDL_TimerCallback callback, void *param)
  334. {
  335. Uint32 new_timeout;
  336. new_timeout = callback(interval, param);
  337. if (new_timeout != 0) {
  338. entry->timeoutID = EM_ASM_INT({
  339. return Browser.safeSetTimeout(function() {
  340. dynCall('viiii', $0, [$1, $2, $3, $4]);
  341. }, $2);
  342. }, &SDL_Emscripten_TimerHelper, entry, interval, callback, param);
  343. }
  344. }
  345. int
  346. SDL_TimerInit(void)
  347. {
  348. return 0;
  349. }
  350. void
  351. SDL_TimerQuit(void)
  352. {
  353. SDL_TimerData *data = &SDL_timer_data;
  354. SDL_TimerMap *entry;
  355. while (data->timermap) {
  356. entry = data->timermap;
  357. data->timermap = entry->next;
  358. SDL_free(entry);
  359. }
  360. }
  361. SDL_TimerID
  362. SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param)
  363. {
  364. SDL_TimerData *data = &SDL_timer_data;
  365. SDL_TimerMap *entry;
  366. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  367. if (!entry) {
  368. SDL_OutOfMemory();
  369. return 0;
  370. }
  371. entry->timerID = ++data->nextID;
  372. entry->timeoutID = EM_ASM_INT({
  373. return Browser.safeSetTimeout(function() {
  374. dynCall('viiii', $0, [$1, $2, $3, $4]);
  375. }, $2);
  376. }, &SDL_Emscripten_TimerHelper, entry, interval, callback, param);
  377. entry->next = data->timermap;
  378. data->timermap = entry;
  379. return entry->timerID;
  380. }
  381. SDL_bool
  382. SDL_RemoveTimer(SDL_TimerID id)
  383. {
  384. SDL_TimerData *data = &SDL_timer_data;
  385. SDL_TimerMap *prev, *entry;
  386. /* Find the timer */
  387. prev = NULL;
  388. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  389. if (entry->timerID == id) {
  390. if (prev) {
  391. prev->next = entry->next;
  392. } else {
  393. data->timermap = entry->next;
  394. }
  395. break;
  396. }
  397. }
  398. if (entry) {
  399. EM_ASM_({
  400. window.clearTimeout($0);
  401. }, entry->timeoutID);
  402. SDL_free(entry);
  403. return SDL_TRUE;
  404. }
  405. return SDL_FALSE;
  406. }
  407. #endif
  408. /* This is a legacy support function; SDL_GetTicks() returns a Uint32,
  409. which wraps back to zero every ~49 days. The newer SDL_GetTicks64()
  410. doesn't have this problem, so we just wrap that function and clamp to
  411. the low 32-bits for binary compatibility. */
  412. Uint32
  413. SDL_GetTicks(void)
  414. {
  415. return (Uint32) (SDL_GetTicks64() & 0xFFFFFFFF);
  416. }
  417. /* vi: set ts=4 sw=4 expandtab: */