0

Is output

2 2
1 1
0 0
3 3
1610766130 4

normal behavour or bug in my code?

Code:

#ifdef __cplusplus
extern "C" {
#endif

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


#define N_TREADS 5


void *p( void* in )
{
    int w;
    void * word;
    word = in;
    w = *((int*)word);
    usleep((rand() %  1000) + 1000);
    printf( "%i %i\n", *((int*)word),w );
    pthread_exit(NULL);
    return NULL;
}

int main( int argc, char *argv[] )
{
    pthread_t threads[N_TREADS];
    int numberz[N_TREADS];
    int rc,i;
    for(i =0;i< N_TREADS; i++)
    {
        numberz[i]=i;
        rc = pthread_create( &threads[i], NULL, p, (void*)&numberz[i] );
        if( rc )
        {
            printf("error");
            exit( -1 );
        }
    }
    pthread_exit(NULL);
}


#ifdef __cplusplus
}
#endif

2 Answers 2

3

I guess thread 4 returns after the main() stack space has been reused?

You should pthread_join your threads before numberz goes out of scipe.

Sign up to request clarification or add additional context in comments.

1 Comment

That is great. Looks like that most examples on net have save bug.
1

I don't think you want the pthread_exit in main (or in p). But you should probably be using pthread_join to wait for the threads in main then exit.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.