fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5.  
  6. // Let us create a global variable to change it in threads
  7. int g = 0;
  8.  
  9. // The function to be executed by all threads
  10. void *myThreadFun(void *vargp)
  11. {
  12. // Store the value argument passed to this thread
  13. int *myid = (int *)vargp;
  14.  
  15. // Let us create a static variable to observe its changes
  16. static int s = 0;
  17.  
  18. // Change static and global variables
  19. ++s; ++g;
  20.  
  21. // Print the argument, static and global variables
  22. printf("Thread ID: %d, Static: %d, Global: %d\n", *myid, ++s, ++g);
  23. }
  24.  
  25. int main()
  26. {
  27. int i;
  28. pthread_t tid;
  29.  
  30. // Let us create three threads
  31. for (i = 0; i < 3; i++)
  32. pthread_create(&tid, NULL, myThreadFun, (void *)&tid);
  33.  
  34. pthread_exit(NULL);
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 5400KB
stdin
Standard input is empty
stdout
Thread ID: 1746347776, Static: 2, Global: 2
Thread ID: 1746347776, Static: 4, Global: 4
Thread ID: 1746347776, Static: 6, Global: 6