fork download
  1. #include <pthread.h>
  2. #include <stdint.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. static void *worker_thread(void *arg) {
  7. /* Convert pointer back to an integer type of matching width */
  8. intptr_t input = (intptr_t)arg;
  9.  
  10. printf("[Thread] Received argument: %ld\n", (long)input);
  11.  
  12. /* Compute a result and return it via the void* return value */
  13. intptr_t result = input * input;
  14.  
  15. /* Avoid returning pointers to local stack variables; passing an integer
  16.   cast to intptr_t -> void* is safe and avoids heap allocation here. */
  17. return (void *)result;
  18. }
  19.  
  20. int main(void) {
  21. pthread_t tid;
  22. intptr_t value_to_pass = 7;
  23. void *raw_ret = NULL;
  24.  
  25. printf("[Parent] Creating thread with argument: %ld\n", (long)value_to_pass);
  26.  
  27. int rc = pthread_create(&tid, NULL, worker_thread, (void *)value_to_pass);
  28. if (rc != 0) {
  29. fprintf(stderr, "pthread_create failed (code %d)\n", rc);
  30. return EXIT_FAILURE;
  31. }
  32.  
  33. /* Block until the child thread finishes and capture its return pointer */
  34. rc = pthread_join(tid, &raw_ret);
  35. if (rc != 0) {
  36. fprintf(stderr, "pthread_join failed (code %d)\n", rc);
  37. return EXIT_FAILURE;
  38. }
  39.  
  40. intptr_t exit_value = (intptr_t)raw_ret;
  41. printf("[Parent] Thread finished with return value: %ld\n", (long)exit_value);
  42.  
  43. return EXIT_SUCCESS;
  44. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
[Parent] Creating thread with argument: 7
[Thread] Received argument: 7
[Parent] Thread finished with return value: 49