| 276 | } |
| 277 | |
| 278 | SDL_TimerID |
| 279 | SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param) |
| 280 | { |
| 281 | SDL_TimerData *data = &SDL_timer_data; |
| 282 | SDL_Timer *timer; |
| 283 | SDL_TimerMap *entry; |
| 284 | |
| 285 | SDL_AtomicLock(&data->lock); |
| 286 | if (!SDL_AtomicGet(&data->active)) { |
| 287 | if (SDL_TimerInit() < 0) { |
| 288 | SDL_AtomicUnlock(&data->lock); |
| 289 | return 0; |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | timer = data->freelist; |
| 294 | if (timer) { |
| 295 | data->freelist = timer->next; |
| 296 | } |
| 297 | SDL_AtomicUnlock(&data->lock); |
| 298 | |
| 299 | if (timer) { |
| 300 | SDL_RemoveTimer(timer->timerID); |
| 301 | } else { |
| 302 | timer = (SDL_Timer *)SDL_malloc(sizeof(*timer)); |
| 303 | if (!timer) { |
| 304 | SDL_OutOfMemory(); |
| 305 | return 0; |
| 306 | } |
| 307 | } |
| 308 | timer->timerID = SDL_AtomicIncRef(&data->nextID); |
| 309 | timer->callback = callback; |
| 310 | timer->param = param; |
| 311 | timer->interval = interval; |
| 312 | timer->scheduled = SDL_GetTicks() + interval; |
| 313 | SDL_AtomicSet(&timer->canceled, 0); |
| 314 | |
| 315 | entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry)); |
| 316 | if (!entry) { |
| 317 | SDL_free(timer); |
| 318 | SDL_OutOfMemory(); |
| 319 | return 0; |
| 320 | } |
| 321 | entry->timer = timer; |
| 322 | entry->timerID = timer->timerID; |
| 323 | |
| 324 | SDL_LockMutex(data->timermap_lock); |
| 325 | entry->next = data->timermap; |
| 326 | data->timermap = entry; |
| 327 | SDL_UnlockMutex(data->timermap_lock); |
| 328 | |
| 329 | /* Add the timer to the pending list for the timer thread */ |
| 330 | SDL_AtomicLock(&data->lock); |
| 331 | timer->next = data->pending; |
| 332 | data->pending = timer; |
| 333 | SDL_AtomicUnlock(&data->lock); |
| 334 | |
| 335 | /* Wake up the timer thread if necessary */ |