I want create 5 threads to printf
5 nums in array. but when I run the code many times,I found some times there are 6 printf
. What is the reason?
I run the code in ubuntu 14.04 gcc and g++ 4.84. and IDE is 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;
}
The weird output:
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