2012-07-03 119 views
0

我碰到了一个pthread指针数组。每个线程是指读出不同的数据流pthread指针阵列

typedef struct { 
    // ...other stuff 
    pthread_t *threads[MAX_STREAM_COUNT]; 
} stream_manager; 

当我要开始阅读:

void start_reading(stream_manager *sm, int i) { 
    // do some pre processing stuff 
    pthread_create((pthread*) &sm->threads[i], 
           NULL, 
           read_stream_cb, 
         (void*) sm->streams[i]  ); 
} 

当我想停止阅读:

void stop_reading(stream_manager *sm, int i) { 
    iret = pthread_join(*sm->threads[i], NULL); 
    if(iret != 0) { 
    perror("pthread_join returned with error:: "); 
    printf("pthread_join returned with error:: %s\n", strerror(iret)) 
    } 
} 

现在,我read_stream_cb函数只是打印其读取的流的名称。

void* read_stream_cb(stream *strm) { 
    stream *s = (stream*) strm; 
    prinf("%s\n", s->name); 
} 

在主程序中,我初始化了2个不同名称的流。我调用run start_reading(),sleep(3)和stop_reading())。该程序打印流名称罚款3秒,但pthread_join不会成功返回。它返回3并打印出

pthread join error: Operation timed out 
pthread_join returned with errer:: No such process 

我觉得这可能是一个指针问题?我可能只是在加入pthread_join(*sm->streams[i], NULL);时将这些指针与操作顺序混淆。我会更多地考虑。

+1

是吧'SM-> streams'或者'SM-> threads'? – cnicutar

+0

你把'(void *)sm-> streams [i]'放入'pthread_join()'?! – Tobas

回答

3

pthread_create()需要pthread_t*作为其参数,这是传递一个pthread_t**

pthread_create((pthread*) &sm->threads[i], 

作为sm->threadspthread_t*阵列。更改stream_manager到:

typedef struct { 
    // ...other stuff 
    pthread_t threads[MAX_STREAM_COUNT]; /* No longer array of pointers. */ 
} stream_manager; 

并从通话不必要的强制转换为pthread_create()

pthread_join()需要pthread_t

pthread_join(sm->threads[i]); /* Not sm->streams[i]. */