example.c 1010 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * WHAT THIS EXAMPLE DOES
  3. *
  4. * We create a pool of 4 threads and then add 40 tasks to the pool(20 task1
  5. * functions and 20 task2 functions). task1 and task2 simply print which thread is running them.
  6. *
  7. * As soon as we add the tasks to the pool, the threads will run them. It can happen that
  8. * you see a single thread running all the tasks (highly unlikely). It is up the OS to
  9. * decide which thread will run what. So it is not an error of the thread pool but rather
  10. * a decision of the OS.
  11. *
  12. * */
  13. #include <stdio.h>
  14. #include <pthread.h>
  15. #include <stdint.h>
  16. #include "thpool.h"
  17. void task(void *arg){
  18. printf("Thread #%u working on %d\n", (int)pthread_self(), (int) arg);
  19. }
  20. int main(){
  21. puts("Making threadpool with 4 threads");
  22. threadpool thpool = thpool_init(4);
  23. puts("Adding 40 tasks to threadpool");
  24. int i;
  25. for (i=0; i<40; i++){
  26. thpool_add_work(thpool, task, (void*)(uintptr_t)i);
  27. };
  28. thpool_wait(thpool);
  29. puts("Killing threadpool");
  30. thpool_destroy(thpool);
  31. return 0;
  32. }