fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. // Thread function
  6. void* print_numbers(void* arg) {
  7. int thread_id = *(int*)arg;
  8. for(int i = 1; i <= 5; i++) {
  9. printf("Thread %d: %d\n", thread_id, i);
  10. sleep(1); // Simulate work
  11. }
  12. pthread_exit(NULL);
  13. }
  14. int main() {
  15. pthread_t t1, t2;
  16. int id1 = 1, id2 = 2;
  17. // Create threads
  18. pthread_create(&t1, NULL, print_numbers, &id1);
  19. pthread_create(&t2, NULL, print_numbers, &id2);
  20. // Wait for threads to finish
  21. pthread_join(t1, NULL);
  22. pthread_join(t2, NULL);
  23. printf("Both threads finished execution.\n");
  24. return 0;
  25. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Thread 2: 1
Thread 1: 1
Thread 2: 2
Thread 1: 2
Thread 2: 3
Thread 1: 3
Thread 2: 4
Thread 1: 4
Thread 2: 5
Thread 1: 5
Both threads finished execution.