create_join.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * This file is copied from https://web.dev/articles/wasm-threads
  3. */
  4. #include <pthread.h>
  5. #include <stdio.h>
  6. /* Calculate Fibonacci numbers shared function */
  7. int
  8. fibonacci(int iterations)
  9. {
  10. int val = 1;
  11. int last = 0;
  12. if (iterations == 0) {
  13. return 0;
  14. }
  15. for (int i = 1; i < iterations; i++) {
  16. int seq;
  17. seq = val + last;
  18. last = val;
  19. val = seq;
  20. }
  21. return val;
  22. }
  23. int bg = 42;
  24. /* Start function for the background thread */
  25. void *
  26. bg_func(void *arg)
  27. {
  28. int *iter = (void *)arg;
  29. *iter = fibonacci(*iter);
  30. printf("bg number: %d\n", *iter);
  31. return arg;
  32. }
  33. /* Foreground thread and main entry point */
  34. int
  35. main(int argc, char *argv[])
  36. {
  37. int fg_val = 54;
  38. int bg_val = 42;
  39. pthread_t bg_thread;
  40. /* Create the background thread */
  41. if (pthread_create(&bg_thread, NULL, bg_func, &bg_val)) {
  42. printf("Thread create failed");
  43. return 1;
  44. }
  45. /* Calculate on the foreground thread */
  46. fg_val = fibonacci(fg_val);
  47. /* Wait for background thread to finish */
  48. if (pthread_join(bg_thread, NULL)) {
  49. printf("Thread join failed");
  50. return 2;
  51. }
  52. /* Show the result from background and foreground threads */
  53. printf("Fib(42) is %d, Fib(6 * 9) is %d\n", bg_val, fg_val);
  54. return 0;
  55. }