2017-05-10 44 views
0

我想理解为什么我得到这个答案,而我在线程中运行此代码。 我不明白为什么我没有得到不同的我每次价值。 enter image description here多线程打印值在一起

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#define NUM_THREADS 5 

void *printHello(void *threadid) 
{ 
    int tid = *(int*)threadid; 

    printf("Hello World! It's me, thread #%d!\n", tid); 

    pthread_exit(NULL); 
} 

int main(int argc, char *argv[]) 
{ 
    pthread_t threads[NUM_THREADS]; 
    int rc; 
    int i; 

    for (i = 0; i < NUM_THREADS; i++) 
    { 
     printf("In main: creating thread %ld\n", i,); 

     rc = pthread_create(&threads[i], NULL, printHello, &i); 

     if (rc) 
     { 
      printf("ERROR; return code from pthread_create() is %d\n", rc); 
      exit(-1); 
     } 
    } 

    pthread_exit(NULL); 
} 

做所有的线程等待,直到他们完成创建他们,然后他们去printHello功能?

回答

1

当您创建新线程时,没有固定的线程执行顺序。主线程和新创建的线程将简单地同时运行。

相对于你的i变量的问题是,你正在传递的i地址pthread_create功能。由于此变量在随后的循环迭代中得到更新,因此当您通过其地址(来自printHello回调函数内)访问它时,其值将发生变化。在您的输出中,我们可以看到在main函数中的循环已经在任何产生的线程输出任何内容之前完成,因为i已经达到了NUM_THREADS限制。

如果你想要的东西是确定的,然后创建一个新的变量来保存线程ID,并在地址位置通过该线程,而不是:

int threadIds[NUM_THREADS]; 
int rc; 
int i; 

for (i = 0; i < NUM_THREADS; i++) 
{ 
    threadIds[i] = i; 
    rc = pthread_create(&threads[i], NULL, printHello, threadIds + i); 
} 

此外,主线程,直到所有的块产生的线程已经完成执行,并且不会在main函数中调用pthread_exit。它不在pthread中运行,所以它不需要退出。

+0

谢谢。这是明确的答案 –