2011-05-19 69 views
0

输出并行线程异常behavoiur

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 

回答

3

我猜线程在main()堆栈空间后4个回报得到了重用?

你应该pthread_join你的线程numberz走出scipe。

+0

这很棒。看起来像网上的大多数例子都有保存错误。 – 2011-05-19 11:19:49

1

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