fork(2) download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. #define THREADS 3
  5.  
  6. void* task(void* arg) {
  7. int id = *(int*)arg;
  8. printf("Thread %d started\n", id);
  9. printf("Thread %d finished\n", id);
  10. return NULL;
  11. }
  12.  
  13. int main() {
  14. pthread_t threads[THREADS];
  15. int ids[THREADS];
  16.  
  17. for(int i = 0; i < THREADS; i++) {
  18. ids[i] = i + 1;
  19. pthread_create(&threads[i], NULL, task, &ids[i]);
  20. }
  21.  
  22. for(int i = 0; i < THREADS; i++) {
  23. pthread_join(threads[i], NULL);
  24. }
  25.  
  26. printf("All threads completed\n");
  27.  
  28. return 0;
  29. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Thread 3 started
Thread 3 finished
Thread 2 started
Thread 2 finished
Thread 1 started
Thread 1 finished
All threads completed