testsem.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely.
  9. */
  10. /* Simple test of the SDL semaphore code */
  11. #include <signal.h>
  12. #include <SDL3/SDL.h>
  13. #include <SDL3/SDL_main.h>
  14. #include <SDL3/SDL_test.h>
  15. #define NUM_THREADS 10
  16. /* This value should be smaller than the maximum count of the */
  17. /* semaphore implementation: */
  18. #define NUM_OVERHEAD_OPS 10000
  19. #define NUM_OVERHEAD_OPS_MULT 10
  20. static SDL_Semaphore *sem;
  21. static int alive;
  22. typedef struct Thread_State
  23. {
  24. SDL_Thread *thread;
  25. int number;
  26. bool flag;
  27. int loop_count;
  28. int content_count;
  29. } Thread_State;
  30. static void log_usage(char *progname, SDLTest_CommonState *state) {
  31. static const char *options[] = { "[--no-threads]", "init_value", NULL };
  32. SDLTest_CommonLogUsage(state, progname, options);
  33. }
  34. static void
  35. killed(int sig)
  36. {
  37. alive = 0;
  38. }
  39. static int SDLCALL
  40. ThreadFuncRealWorld(void *data)
  41. {
  42. Thread_State *state = (Thread_State *)data;
  43. while (alive) {
  44. SDL_WaitSemaphore(sem);
  45. SDL_Log("Thread number %d has got the semaphore (value = %" SDL_PRIu32 ")!",
  46. state->number, SDL_GetSemaphoreValue(sem));
  47. SDL_Delay(200);
  48. SDL_SignalSemaphore(sem);
  49. SDL_Log("Thread number %d has released the semaphore (value = %" SDL_PRIu32 ")!",
  50. state->number, SDL_GetSemaphoreValue(sem));
  51. ++state->loop_count;
  52. SDL_Delay(1); /* For the scheduler */
  53. }
  54. SDL_Log("Thread number %d exiting.", state->number);
  55. return 0;
  56. }
  57. static void
  58. TestRealWorld(int init_sem)
  59. {
  60. Thread_State thread_states[NUM_THREADS] = { { 0 } };
  61. int i;
  62. int loop_count;
  63. sem = SDL_CreateSemaphore(init_sem);
  64. SDL_Log("Running %d threads, semaphore value = %d", NUM_THREADS,
  65. init_sem);
  66. alive = 1;
  67. /* Create all the threads */
  68. for (i = 0; i < NUM_THREADS; ++i) {
  69. char name[64];
  70. (void)SDL_snprintf(name, sizeof(name), "Thread%u", (unsigned int)i);
  71. thread_states[i].number = i;
  72. thread_states[i].thread = SDL_CreateThread(ThreadFuncRealWorld, name, (void *)&thread_states[i]);
  73. }
  74. /* Wait 10 seconds */
  75. SDL_Delay(10 * 1000);
  76. /* Wait for all threads to finish */
  77. SDL_Log("Waiting for threads to finish");
  78. alive = 0;
  79. loop_count = 0;
  80. for (i = 0; i < NUM_THREADS; ++i) {
  81. SDL_WaitThread(thread_states[i].thread, NULL);
  82. loop_count += thread_states[i].loop_count;
  83. }
  84. SDL_Log("Finished waiting for threads, ran %d loops in total", loop_count);
  85. SDL_Log("%s", "");
  86. SDL_DestroySemaphore(sem);
  87. }
  88. static void
  89. TestWaitTimeout(void)
  90. {
  91. Uint64 start_ticks;
  92. Uint64 end_ticks;
  93. Uint64 duration;
  94. bool result;
  95. sem = SDL_CreateSemaphore(0);
  96. SDL_Log("Waiting 2 seconds on semaphore");
  97. start_ticks = SDL_GetTicks();
  98. result = SDL_WaitSemaphoreTimeout(sem, 2000);
  99. end_ticks = SDL_GetTicks();
  100. duration = end_ticks - start_ticks;
  101. /* Accept a little offset in the effective wait */
  102. SDL_Log("Wait took %" SDL_PRIu64 " milliseconds", duration);
  103. SDL_Log("%s", "");
  104. SDL_assert(duration > 1900 && duration < 2050);
  105. /* Check to make sure the return value indicates timed out */
  106. if (result) {
  107. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_WaitSemaphoreTimeout returned: %d; expected: false", result);
  108. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s", "");
  109. }
  110. SDL_DestroySemaphore(sem);
  111. }
  112. static void
  113. TestOverheadUncontended(void)
  114. {
  115. Uint64 start_ticks;
  116. Uint64 end_ticks;
  117. Uint64 duration;
  118. int i, j;
  119. sem = SDL_CreateSemaphore(0);
  120. SDL_Log("Doing %d uncontended Post/Wait operations on semaphore", NUM_OVERHEAD_OPS * NUM_OVERHEAD_OPS_MULT);
  121. start_ticks = SDL_GetTicks();
  122. for (i = 0; i < NUM_OVERHEAD_OPS_MULT; i++) {
  123. for (j = 0; j < NUM_OVERHEAD_OPS; j++) {
  124. SDL_SignalSemaphore(sem);
  125. }
  126. for (j = 0; j < NUM_OVERHEAD_OPS; j++) {
  127. SDL_WaitSemaphore(sem);
  128. }
  129. }
  130. end_ticks = SDL_GetTicks();
  131. duration = end_ticks - start_ticks;
  132. SDL_Log("Took %" SDL_PRIu64 " milliseconds", duration);
  133. SDL_Log("%s", "");
  134. SDL_DestroySemaphore(sem);
  135. }
  136. static int SDLCALL
  137. ThreadFuncOverheadContended(void *data)
  138. {
  139. Thread_State *state = (Thread_State *)data;
  140. if (state->flag) {
  141. while (alive) {
  142. if (!SDL_TryWaitSemaphore(sem)) {
  143. ++state->content_count;
  144. }
  145. ++state->loop_count;
  146. }
  147. } else {
  148. while (alive) {
  149. /* Timeout needed to allow check on alive flag */
  150. if (!SDL_WaitSemaphoreTimeout(sem, 50)) {
  151. ++state->content_count;
  152. }
  153. ++state->loop_count;
  154. }
  155. }
  156. return 0;
  157. }
  158. static void
  159. TestOverheadContended(bool try_wait)
  160. {
  161. Uint64 start_ticks;
  162. Uint64 end_ticks;
  163. Uint64 duration;
  164. Thread_State thread_states[NUM_THREADS] = { { 0 } };
  165. char textBuffer[1024];
  166. int loop_count;
  167. int content_count;
  168. int i, j;
  169. size_t len;
  170. sem = SDL_CreateSemaphore(0);
  171. SDL_Log("Doing %d contended %s operations on semaphore using %d threads",
  172. NUM_OVERHEAD_OPS * NUM_OVERHEAD_OPS_MULT, try_wait ? "Post/TryWait" : "Post/WaitTimeout", NUM_THREADS);
  173. alive = 1;
  174. /* Create multiple threads to starve the semaphore and cause contention */
  175. for (i = 0; i < NUM_THREADS; ++i) {
  176. char name[64];
  177. (void)SDL_snprintf(name, sizeof(name), "Thread%u", (unsigned int)i);
  178. thread_states[i].flag = try_wait;
  179. thread_states[i].thread = SDL_CreateThread(ThreadFuncOverheadContended, name, (void *)&thread_states[i]);
  180. }
  181. start_ticks = SDL_GetTicks();
  182. for (i = 0; i < NUM_OVERHEAD_OPS_MULT; i++) {
  183. for (j = 0; j < NUM_OVERHEAD_OPS; j++) {
  184. SDL_SignalSemaphore(sem);
  185. }
  186. /* Make sure threads consumed everything */
  187. while (SDL_GetSemaphoreValue(sem)) {
  188. /* Friendlier with cooperative threading models */
  189. SDL_DelayNS(1);
  190. }
  191. }
  192. end_ticks = SDL_GetTicks();
  193. alive = 0;
  194. loop_count = 0;
  195. content_count = 0;
  196. for (i = 0; i < NUM_THREADS; ++i) {
  197. SDL_WaitThread(thread_states[i].thread, NULL);
  198. loop_count += thread_states[i].loop_count;
  199. content_count += thread_states[i].content_count;
  200. }
  201. SDL_assert_release((loop_count - content_count) == NUM_OVERHEAD_OPS * NUM_OVERHEAD_OPS_MULT);
  202. duration = end_ticks - start_ticks;
  203. SDL_Log("Took %" SDL_PRIu64 " milliseconds, threads %s %d out of %d times in total (%.2f%%)",
  204. duration, try_wait ? "where contended" : "timed out", content_count,
  205. loop_count, ((float)content_count * 100) / loop_count);
  206. /* Print how many semaphores where consumed per thread */
  207. (void)SDL_snprintf(textBuffer, sizeof(textBuffer), "{ ");
  208. for (i = 0; i < NUM_THREADS; ++i) {
  209. if (i > 0) {
  210. len = SDL_strlen(textBuffer);
  211. (void)SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, ", ");
  212. }
  213. len = SDL_strlen(textBuffer);
  214. (void)SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, "%d", thread_states[i].loop_count - thread_states[i].content_count);
  215. }
  216. len = SDL_strlen(textBuffer);
  217. (void)SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, " }");
  218. SDL_Log("%s", textBuffer);
  219. SDL_DestroySemaphore(sem);
  220. }
  221. int main(int argc, char **argv)
  222. {
  223. int arg_count = 0;
  224. int i;
  225. int init_sem = 0;
  226. bool enable_threads = true;
  227. SDLTest_CommonState *state;
  228. /* Initialize test framework */
  229. state = SDLTest_CommonCreateState(argv, 0);
  230. if (!state) {
  231. return 1;
  232. }
  233. /* Parse commandline */
  234. for (i = 1; i < argc;) {
  235. int consumed;
  236. consumed = SDLTest_CommonArg(state, i);
  237. if (consumed == 0) {
  238. consumed = -1;
  239. if (SDL_strcasecmp(argv[i], "--no-threads") == 0) {
  240. enable_threads = false;
  241. consumed = 1;
  242. } else if (arg_count == 0) {
  243. char *endptr;
  244. init_sem = SDL_strtol(argv[i], &endptr, 0);
  245. if (endptr != argv[i] && *endptr == '\0') {
  246. arg_count++;
  247. consumed = 1;
  248. }
  249. }
  250. }
  251. if (consumed <= 0) {
  252. log_usage(argv[0], state);
  253. return 1;
  254. }
  255. i += consumed;
  256. }
  257. if (arg_count != 1) {
  258. log_usage(argv[0], state);
  259. return 1;
  260. }
  261. /* Load the SDL library */
  262. if (!SDL_Init(0)) {
  263. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
  264. return 1;
  265. }
  266. (void)signal(SIGTERM, killed);
  267. (void)signal(SIGINT, killed);
  268. if (enable_threads) {
  269. if (init_sem > 0) {
  270. TestRealWorld(init_sem);
  271. }
  272. TestWaitTimeout();
  273. }
  274. TestOverheadUncontended();
  275. if (enable_threads) {
  276. TestOverheadContended(false);
  277. TestOverheadContended(true);
  278. }
  279. SDL_Quit();
  280. SDLTest_CommonDestroyState(state);
  281. return 0;
  282. }