SDL_timer.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 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__) || !defined(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. {
  45. /* Data used by the main thread */
  46. SDL_Thread *thread;
  47. SDL_atomic_t nextID;
  48. SDL_TimerMap *timermap;
  49. SDL_mutex *timermap_lock;
  50. /* Padding to separate cache lines between threads */
  51. char cache_pad[SDL_CACHELINE_SIZE];
  52. /* Data used to communicate with the timer thread */
  53. SDL_SpinLock lock;
  54. SDL_sem *sem;
  55. SDL_Timer *pending;
  56. SDL_Timer *freelist;
  57. SDL_atomic_t active;
  58. /* List of timers - this is only touched by the timer thread */
  59. SDL_Timer *timers;
  60. } SDL_TimerData;
  61. static SDL_TimerData SDL_timer_data;
  62. /* The idea here is that any thread might add a timer, but a single
  63. * thread manages the active timer queue, sorted by scheduling time.
  64. *
  65. * Timers are removed by simply setting a canceled flag
  66. */
  67. static void 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 SDL_TimerThread(void *_data)
  85. {
  86. SDL_TimerData *data = (SDL_TimerData *)_data;
  87. SDL_Timer *pending;
  88. SDL_Timer *current;
  89. SDL_Timer *freelist_head = NULL;
  90. SDL_Timer *freelist_tail = NULL;
  91. Uint32 tick, now, interval, delay;
  92. /* Threaded timer loop:
  93. * 1. Queue timers added by other threads
  94. * 2. Handle any timers that should dispatch this cycle
  95. * 3. Wait until next dispatch time or new timer arrives
  96. */
  97. for (;;) {
  98. /* Pending and freelist maintenance */
  99. SDL_AtomicLock(&data->lock);
  100. {
  101. /* Get any timers ready to be queued */
  102. pending = data->pending;
  103. data->pending = NULL;
  104. /* Make any unused timer structures available */
  105. if (freelist_head) {
  106. freelist_tail->next = data->freelist;
  107. data->freelist = freelist_head;
  108. }
  109. }
  110. SDL_AtomicUnlock(&data->lock);
  111. /* Sort the pending timers into our list */
  112. while (pending) {
  113. current = pending;
  114. pending = pending->next;
  115. SDL_AddTimerInternal(data, current);
  116. }
  117. freelist_head = NULL;
  118. freelist_tail = NULL;
  119. /* Check to see if we're still running, after maintenance */
  120. if (!SDL_AtomicGet(&data->active)) {
  121. break;
  122. }
  123. /* Initial delay if there are no timers */
  124. delay = SDL_MUTEX_MAXWAIT;
  125. tick = SDL_GetTicks();
  126. /* Process all the pending timers for this tick */
  127. while (data->timers) {
  128. current = data->timers;
  129. if ((Sint32)(tick - current->scheduled) < 0) {
  130. /* Scheduled for the future, wait a bit */
  131. delay = (current->scheduled - tick);
  132. break;
  133. }
  134. /* We're going to do something with this timer */
  135. data->timers = current->next;
  136. if (SDL_AtomicGet(&current->canceled)) {
  137. interval = 0;
  138. } else {
  139. interval = current->callback(current->interval, current->param);
  140. }
  141. if (interval > 0) {
  142. /* Reschedule this timer */
  143. current->interval = interval;
  144. current->scheduled = tick + interval;
  145. SDL_AddTimerInternal(data, current);
  146. } else {
  147. if (!freelist_head) {
  148. freelist_head = current;
  149. }
  150. if (freelist_tail) {
  151. freelist_tail->next = current;
  152. }
  153. freelist_tail = current;
  154. SDL_AtomicSet(&current->canceled, 1);
  155. }
  156. }
  157. /* Adjust the delay based on processing time */
  158. now = SDL_GetTicks();
  159. interval = (now - tick);
  160. if (interval > delay) {
  161. delay = 0;
  162. } else {
  163. delay -= interval;
  164. }
  165. /* Note that each time a timer is added, this will return
  166. immediately, but we process the timers added all at once.
  167. That's okay, it just means we run through the loop a few
  168. extra times.
  169. */
  170. SDL_SemWaitTimeout(data->sem, delay);
  171. }
  172. return 0;
  173. }
  174. int SDL_TimerInit(void)
  175. {
  176. SDL_TimerData *data = &SDL_timer_data;
  177. if (!SDL_AtomicGet(&data->active)) {
  178. const char *name = "SDLTimer";
  179. data->timermap_lock = SDL_CreateMutex();
  180. if (!data->timermap_lock) {
  181. return -1;
  182. }
  183. data->sem = SDL_CreateSemaphore(0);
  184. if (!data->sem) {
  185. SDL_DestroyMutex(data->timermap_lock);
  186. return -1;
  187. }
  188. SDL_AtomicSet(&data->active, 1);
  189. /* Timer threads use a callback into the app, so we can't set a limited stack size here. */
  190. data->thread = SDL_CreateThreadInternal(SDL_TimerThread, name, 0, data);
  191. if (!data->thread) {
  192. SDL_TimerQuit();
  193. return -1;
  194. }
  195. SDL_AtomicSet(&data->nextID, 1);
  196. }
  197. return 0;
  198. }
  199. void SDL_TimerQuit(void)
  200. {
  201. SDL_TimerData *data = &SDL_timer_data;
  202. SDL_Timer *timer;
  203. SDL_TimerMap *entry;
  204. if (SDL_AtomicCAS(&data->active, 1, 0)) { /* active? Move to inactive. */
  205. /* Shutdown the timer thread */
  206. if (data->thread) {
  207. SDL_SemPost(data->sem);
  208. SDL_WaitThread(data->thread, NULL);
  209. data->thread = NULL;
  210. }
  211. SDL_DestroySemaphore(data->sem);
  212. data->sem = NULL;
  213. /* Clean up the timer entries */
  214. while (data->timers) {
  215. timer = data->timers;
  216. data->timers = timer->next;
  217. SDL_free(timer);
  218. }
  219. while (data->freelist) {
  220. timer = data->freelist;
  221. data->freelist = timer->next;
  222. SDL_free(timer);
  223. }
  224. while (data->timermap) {
  225. entry = data->timermap;
  226. data->timermap = entry->next;
  227. SDL_free(entry);
  228. }
  229. SDL_DestroyMutex(data->timermap_lock);
  230. data->timermap_lock = NULL;
  231. }
  232. }
  233. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param)
  234. {
  235. SDL_TimerData *data = &SDL_timer_data;
  236. SDL_Timer *timer;
  237. SDL_TimerMap *entry;
  238. SDL_AtomicLock(&data->lock);
  239. if (!SDL_AtomicGet(&data->active)) {
  240. if (SDL_TimerInit() < 0) {
  241. SDL_AtomicUnlock(&data->lock);
  242. return 0;
  243. }
  244. }
  245. timer = data->freelist;
  246. if (timer) {
  247. data->freelist = timer->next;
  248. }
  249. SDL_AtomicUnlock(&data->lock);
  250. if (timer) {
  251. SDL_RemoveTimer(timer->timerID);
  252. } else {
  253. timer = (SDL_Timer *)SDL_malloc(sizeof(*timer));
  254. if (!timer) {
  255. SDL_OutOfMemory();
  256. return 0;
  257. }
  258. }
  259. timer->timerID = SDL_AtomicIncRef(&data->nextID);
  260. timer->callback = callback;
  261. timer->param = param;
  262. timer->interval = interval;
  263. timer->scheduled = SDL_GetTicks() + interval;
  264. SDL_AtomicSet(&timer->canceled, 0);
  265. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  266. if (!entry) {
  267. SDL_free(timer);
  268. SDL_OutOfMemory();
  269. return 0;
  270. }
  271. entry->timer = timer;
  272. entry->timerID = timer->timerID;
  273. SDL_LockMutex(data->timermap_lock);
  274. entry->next = data->timermap;
  275. data->timermap = entry;
  276. SDL_UnlockMutex(data->timermap_lock);
  277. /* Add the timer to the pending list for the timer thread */
  278. SDL_AtomicLock(&data->lock);
  279. timer->next = data->pending;
  280. data->pending = timer;
  281. SDL_AtomicUnlock(&data->lock);
  282. /* Wake up the timer thread if necessary */
  283. SDL_SemPost(data->sem);
  284. return entry->timerID;
  285. }
  286. SDL_bool SDL_RemoveTimer(SDL_TimerID id)
  287. {
  288. SDL_TimerData *data = &SDL_timer_data;
  289. SDL_TimerMap *prev, *entry;
  290. SDL_bool canceled = SDL_FALSE;
  291. /* Find the timer */
  292. SDL_LockMutex(data->timermap_lock);
  293. prev = NULL;
  294. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  295. if (entry->timerID == id) {
  296. if (prev) {
  297. prev->next = entry->next;
  298. } else {
  299. data->timermap = entry->next;
  300. }
  301. break;
  302. }
  303. }
  304. SDL_UnlockMutex(data->timermap_lock);
  305. if (entry) {
  306. if (!SDL_AtomicGet(&entry->timer->canceled)) {
  307. SDL_AtomicSet(&entry->timer->canceled, 1);
  308. canceled = SDL_TRUE;
  309. }
  310. SDL_free(entry);
  311. }
  312. return canceled;
  313. }
  314. #else
  315. #include <emscripten/emscripten.h>
  316. #include <emscripten/eventloop.h>
  317. typedef struct _SDL_TimerMap
  318. {
  319. int timerID;
  320. int timeoutID;
  321. Uint32 interval;
  322. SDL_TimerCallback callback;
  323. void *param;
  324. struct _SDL_TimerMap *next;
  325. } SDL_TimerMap;
  326. typedef struct
  327. {
  328. int nextID;
  329. SDL_TimerMap *timermap;
  330. } SDL_TimerData;
  331. static SDL_TimerData SDL_timer_data;
  332. static void SDL_Emscripten_TimerHelper(void *userdata)
  333. {
  334. SDL_TimerMap *entry = (SDL_TimerMap *)userdata;
  335. entry->interval = entry->callback(entry->interval, entry->param);
  336. if (entry->interval > 0) {
  337. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  338. entry->interval,
  339. entry);
  340. }
  341. }
  342. int SDL_TimerInit(void)
  343. {
  344. return 0;
  345. }
  346. void SDL_TimerQuit(void)
  347. {
  348. SDL_TimerData *data = &SDL_timer_data;
  349. SDL_TimerMap *entry;
  350. while (data->timermap) {
  351. entry = data->timermap;
  352. data->timermap = entry->next;
  353. SDL_free(entry);
  354. }
  355. }
  356. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param)
  357. {
  358. SDL_TimerData *data = &SDL_timer_data;
  359. SDL_TimerMap *entry;
  360. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  361. if (!entry) {
  362. SDL_OutOfMemory();
  363. return 0;
  364. }
  365. entry->timerID = ++data->nextID;
  366. entry->callback = callback;
  367. entry->param = param;
  368. entry->interval = interval;
  369. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  370. entry->interval,
  371. entry);
  372. entry->next = data->timermap;
  373. data->timermap = entry;
  374. return entry->timerID;
  375. }
  376. SDL_bool SDL_RemoveTimer(SDL_TimerID id)
  377. {
  378. SDL_TimerData *data = &SDL_timer_data;
  379. SDL_TimerMap *prev, *entry;
  380. /* Find the timer */
  381. prev = NULL;
  382. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  383. if (entry->timerID == id) {
  384. if (prev) {
  385. prev->next = entry->next;
  386. } else {
  387. data->timermap = entry->next;
  388. }
  389. break;
  390. }
  391. }
  392. if (entry) {
  393. emscripten_clear_timeout(entry->timeoutID);
  394. SDL_free(entry);
  395. return SDL_TRUE;
  396. }
  397. return SDL_FALSE;
  398. }
  399. #endif
  400. /* This is a legacy support function; SDL_GetTicks() returns a Uint32,
  401. which wraps back to zero every ~49 days. The newer SDL_GetTicks64()
  402. doesn't have this problem, so we just wrap that function and clamp to
  403. the low 32-bits for binary compatibility. */
  404. Uint32 SDL_GetTicks(void)
  405. {
  406. return (Uint32)(SDL_GetTicks64() & 0xFFFFFFFF);
  407. }
  408. /* vi: set ts=4 sw=4 expandtab: */