PThread 创建和终止

PThread Creation and Termination

我是 使用 c 进行 Pthread 编程的新手 我恰好从网上拿了下面的代码

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5
void *PrintHello(void *threadid)
{
  long tid;
  tid = (long)threadid;
  printf("Hello World! It's me, thread #%ld!\n", tid);
  pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
    int rc;
   long t;
    for(t=0; t<NUM_THREADS; t++){
       printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
        if (rc)
         {
     printf("ERROR; return code from pthread_create() is %d\n",  rc);    
          exit(-1);
          }
    }

       /* Last thing that main() should do */
       pthread_exit(NULL);
}

每次我 运行 上面的代码收到的输出都不同。 错误的原因是什么?

我不知道你的程序有什么错误。它可以执行 perfectly.when 线程被创建,它的 运行 时间是你无法控制的,你不知道它定位到哪个时间,这取决于你的 OS。所以每个输出都是不同的