no_pthread.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (C) 2022 Amazon.com Inc. or its affiliates. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #ifndef __wasi__
  6. #error This example only compiles to WASM/WASI target
  7. #endif
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <assert.h>
  11. #include "wasi_thread_start.h"
  12. static const int64_t SECOND = 1000 * 1000 * 1000;
  13. typedef struct {
  14. start_args_t base;
  15. int th_ready;
  16. int value;
  17. int thread_id;
  18. } shared_t;
  19. void
  20. __wasi_thread_start_C(int thread_id, int *start_arg)
  21. {
  22. shared_t *data = (shared_t *)start_arg;
  23. printf("New thread ID: %d, starting parameter: %d\n", thread_id,
  24. data->value);
  25. data->thread_id = thread_id;
  26. data->value += 8;
  27. printf("Updated value: %d\n", data->value);
  28. __atomic_store_n(&data->th_ready, 1, __ATOMIC_SEQ_CST);
  29. __builtin_wasm_memory_atomic_notify(&data->th_ready, 1);
  30. }
  31. int
  32. main(int argc, char **argv)
  33. {
  34. shared_t data = { { NULL }, 0, 52, -1 };
  35. int thread_id;
  36. int ret = EXIT_SUCCESS;
  37. if (!start_args_init(&data.base)) {
  38. printf("Stack allocation for thread failed\n");
  39. return EXIT_FAILURE;
  40. }
  41. thread_id = __wasi_thread_spawn(&data);
  42. if (thread_id < 0) {
  43. printf("Failed to create thread: %d\n", thread_id);
  44. ret = EXIT_FAILURE;
  45. goto final;
  46. }
  47. if (__builtin_wasm_memory_atomic_wait32(&data.th_ready, 0, SECOND) == 2) {
  48. printf("Timeout\n");
  49. ret = EXIT_FAILURE;
  50. goto final;
  51. }
  52. printf("Thread completed, new value: %d, thread id: %d\n", data.value,
  53. data.thread_id);
  54. assert(thread_id == data.thread_id);
  55. final:
  56. start_args_deinit(&data.base);
  57. return ret;
  58. }