当main()返回时,Linux线程如何运行

时间:2018-08-02 08:58:17

标签: c linux multithreading pthreads

我想创建5个线程来printf 5个数组中的数字。但是当我多次运行代码时,发现有时有6 printf。是什么原因?

我在ubuntu 14.04 gcc和g ++ 4.84中运行代码。 IDE是qtcreator 5.7

#include <stdio.h>    
#include <pthread.h> 

void* Test(void* p)
{
    static int i=0;
    i++;
    printf("test i = %d kk = %d kk = %x\n",i,*((int*)p),p);
}
int main(int argc, char *argv[])
{    
    int n = 0;
    int thread[5] = {0};
    int ss = 0;
    int kk[5] = {0,1,2,3,4};
    for(int i = 0;i<5;i++)
    {
       n = pthread_create((pthread_t*)&thread[i],NULL,Test,(void*)(kk+i));
       printf("for i=%d %x\n",i,kk+i);    
    }
    printf("main return \n");   
    return 0;
}

奇怪的输出:

for i=0 d0af09b0
test i = 1 kk = 0 kk = d0af09b0 
for i=1 d0af09b4
test i = 2 kk = 1 kk = d0af09b4  
for i=2 d0af09b8
test i = 3 kk = 2 kk = d0af09b8  
for i=3 d0af09bc
test i = 4 kk = 3 kk = d0af09bc  
for i=4 d0af09c0
main return 
test i = 5 kk = 4 kk = d0af09c0
test i = 5 kk = 4 kk = d0af09c0 

0 个答案:

没有答案