1

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 
kabanus
  • 24,623
  • 6
  • 41
  • 74
Sranly
  • 11
  • 2
  • 4
    Please post a minimal code example and format your text. – kabanus Aug 02 '18 at 08:59
  • Use the [edit](https://stackoverflow.com/posts/51649563/edit) button and put in the question, properly formatted. Post something that you can easily read yourself. – kabanus Aug 02 '18 at 09:52
  • @kabanus thanks for help – Sranly Aug 02 '18 at 10:29
  • No problem, much better. – kabanus Aug 02 '18 at 10:31
  • The "extra output" is due to a bug in glibc implementation. See the duplicate. When the main thread returns, it exits the whole process (i.e., all the threads die). Also you have *data race* in the access to `i` in the threads. – P.P Aug 02 '18 at 10:37
  • `pthread_join()` is probably your safest option. Right now there is a race condition between main exiting and the threads running. – kabanus Aug 02 '18 at 10:43

0 Answers0