开发者

pthread unusual behavoiur

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜