Guest User

Untitled

a guest
Apr 25th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <setjmp.h>
  4. #include <unistd.h>
  5. #include <pthread.h>
  6.  
  7. /*Async style call example in C*/
  8.  
  9. // Used for threads NOTE the starting value is zero.
  10. static int TOTAL = 0;
  11.  
  12. // Used for async style return
  13. static jmp_buf ENVBUF;
  14.  
  15. // The function a thread is invoked with.
  16. void* threadJob(void *vargp)
  17. {
  18. sleep(4);
  19. puts("Done sleeping"); // This statement doesn't get called, as the call is async.
  20. TOTAL += 300;
  21. return NULL;
  22. }
  23.  
  24. //This function orchestrates the workers
  25. void callWorkers(void)
  26. {
  27. pthread_t worker1;
  28. pthread_t worker2;
  29.  
  30. // Starts the workers,
  31. pthread_create(&worker1, NULL, threadJob, NULL);
  32. pthread_create(&worker2, NULL, threadJob, NULL);
  33.  
  34. // jumps out of the current stack frame, hence not waiting for the threads to finish.
  35. longjmp(ENVBUF, 1);
  36. }
  37.  
  38. int main(void) {
  39.  
  40. pthread_t worker;
  41.  
  42. if(setjmp(ENVBUF)) // This only runs after longjmp is called.
  43. {
  44.  
  45. printf("async calls commenced, total is still %d\n", TOTAL);
  46. exit(0);
  47. }
  48. else
  49. {
  50. printf("Calling worker threads, total is now %d\n", TOTAL);
  51. callWorkers();
  52. }
  53. return 0;
  54. }
Add Comment
Please, Sign In to add comment