Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5.  
  6. #define THREAD_POOL_SIZE 2
  7.  
  8. void *do_work(void *args) {
  9. sleep(2);
  10. int value = *((int*)args);
  11. int sq = value * value;
  12. printf("%d\n", sq);
  13. return NULL;
  14. }
  15.  
  16. int main(void) {
  17. //you need to setup four async operations and wait for them to be done before processing further operations.
  18. pthread_t thread_pool[THREAD_POOL_SIZE];
  19. int proc_items[] = { 1, 8, 17, 12, 13, 14, 19, 22, 31, 56, 43, 77 };
  20.  
  21. int items_left = THREAD_POOL_SIZE;
  22. for (int i=0; i<12; ++i) {
  23. int idx = i % THREAD_POOL_SIZE;
  24. pthread_create(&thread_pool[idx], NULL, do_work, (void*)&proc_items[i]);
  25. items_left--;
  26.  
  27. if (items_left == 0) {
  28. void *retval;
  29. pthread_join(thread_pool[(i - (THREAD_POOL_SIZE - 1)) % THREAD_POOL_SIZE], &retval);
  30. items_left++;
  31. }
  32. }
  33.  
  34. return EXIT_SUCCESS;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement