在Linux中使用Pthreads

ama*_*yot -3 c linux pthreads

我在下面有一个简单的程序,它打印创建的每个线程的线程ID.

#include <stdio.h>
#include <pthread.h>
#define NUM_THREAD 5

void *runner(void *param);

int main()
{
     int i;
     pthread_t tid[NUM_THREAD];

     for(i = 0; i < NUM_THREAD; i++){
         pthread_create(&tid[i], NULL, runner, NULL);
         printf("%u\n", (unsigned int) pthread_self());
     }

//   for(i = 0; i < NUM_THREAD; i++)
//       pthread_join(tid[i], NULL);
}

void *runner(void *param)
{
    /* do some work */

    pthread_exit(0);
}
Run Code Online (Sandbox Code Playgroud)

代码运行正常,给我正确的输出.

1527895872
1527895872 
1527895872
1527895872
1527895872
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么线程ID是相同的?

Zif*_*ion 5

因为您正在打印线程ID main(),而不是线程本身.您需要移动printf()到作为线程运行的代码,即runner().

#include <stdio.h>
#include <pthread.h>
#define NUM_THREAD 5

void *runner(void *param);

int main()
{
     int i;
     pthread_t tid[NUM_THREAD];

     for(i = 0; i < NUM_THREAD; i++){
         pthread_create(&tid[i], NULL, runner, NULL);
         // printf("%u\n", (unsigned int) pthread_self()); // <----- from here
     }

//   for(i = 0; i < NUM_THREAD; i++)
//       pthread_join(tid[i], NULL);
}

void *runner(void *param)
{
    printf("%u\n", (unsigned int) pthread_self()); // <-------- to here

    /* do some work */

    pthread_exit(0);
}
Run Code Online (Sandbox Code Playgroud)