【问题标题】:pthread array of pointerspthread 指针数组
【发布时间】:2012-07-03 19:26:33
【问题描述】:

我对一组 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); 中这些指针的操作顺序感到困惑。我会进一步研究。

【问题讨论】:

  • sm->streams还是sm->threads
  • 你把(void*) sm->streams[i] 放入pthread_join() ?!

标签: c pointers pthreads


【解决方案1】:

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]. */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多