fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4.  
  5. // Function executed by each thread
  6. void* thread_function(void* arg) {
  7. int thread_num = *(int*)arg; // get thread number from argument
  8. printf("Hello from Thread %d! (Thread ID: %lu)\n", thread_num, pthread_self());
  9. return NULL;
  10. }
  11.  
  12. int main() {
  13. int num_threads = 5; // Number of threads to create
  14. pthread_t threads[num_threads]; // Thread handles
  15. int thread_args[num_threads]; // Arguments for each thread
  16.  
  17. // Create multiple threads
  18. for (int i = 0; i < num_threads; i++) {
  19. thread_args[i] = i + 1; // Thread numbering starts from 1
  20. if (pthread_create(&threads[i], NULL, thread_function, &thread_args[i]) != 0) {
  21. perror("Failed to create thread");
  22. exit(1);
  23. }
  24. }
  25.  
  26. // Wait for all threads to finish
  27. for (int i = 0; i < num_threads; i++) {
  28. pthread_join(threads[i], NULL);
  29. }
  30.  
  31. printf("All threads have finished execution.\n");
  32. return 0;
  33. }
  34.  
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Hello from Thread 5! (Thread ID: 23108288497408)
Hello from Thread 4! (Thread ID: 23108290598656)
Hello from Thread 3! (Thread ID: 23108292699904)
Hello from Thread 2! (Thread ID: 23108294801152)
Hello from Thread 1! (Thread ID: 23108296902400)
All threads have finished execution.