tst-gettid.c 932 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <stdlib.h>
  6. void *thread_func(void *arg)
  7. {
  8. printf("Thread %ld:\n", (long)arg);
  9. printf(" PID = %d\n", getpid());
  10. printf(" TID = %d (gettid)\n", gettid());
  11. printf(" pthread ID = %lu\n\n", pthread_self());
  12. return NULL;
  13. }
  14. int main(void)
  15. {
  16. const int NUM_THREADS = 3;
  17. pthread_t threads[NUM_THREADS];
  18. printf("Main thread:\n");
  19. printf(" PID = %d\n", getpid());
  20. printf(" TID = %d (gettid)\n", gettid());
  21. printf(" pthread ID = %lu\n\n", pthread_self());
  22. for (long i = 0; i < NUM_THREADS; i++) {
  23. if (pthread_create(&threads[i], NULL, thread_func, (void *)i) != 0) {
  24. perror("pthread_create");
  25. exit(EXIT_FAILURE);
  26. }
  27. }
  28. for (int i = 0; i < NUM_THREADS; i++) {
  29. pthread_join(threads[i], NULL);
  30. }
  31. return 0;
  32. }