pthread不寻常的行为

时间:2011-05-19 10:58:17

标签: pthreads

输出

2 2
1 1
0 0
3 3
1610766130 4

我的代码中的正常行为或错误?

代码:

#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 个答案:

答案 0 :(得分:3)

我认为在重用main()堆栈空间后,线程4会返回?

pthread_join消失之前,你应该numberz你的主题。

答案 1 :(得分:1)

我认为你不想在main(或p)中使用pthread_exit。但你可能应该使用pthread_join来等待main中的线程然后退出。

相关问题