【问题标题】:Dereferencing an array within a struct being used by ptread_create取消引用 ptread_create 正在使用的结构中的数组
【发布时间】:2013-02-24 22:21:42
【问题描述】:

我的 ThreadData 结构:

typedef struct threadData {
    pthread_t *ths;
} threadData;

其中 *ths 是 pthread_t 的数组。

现在,我创建一个线程,使用以下函数作为操作,该函数在 ths[1] 中创建一个新线程

void *rootThread(threadData *d) {
    pthread_t *b = (*d).ths;
    pthread_create(*(b+1),NULL,someRandomFunction,NULL);
}

但这似乎不起作用。

我不确定我是否很好地取消了 pthread_t 元素的引用。请帮忙!

谢谢,:)。

【问题讨论】:

  • 你是如何分配你的结构踏面数据的?目前,您似乎正在创建线程数据的成员,只是为了作为指针,而不为它分配内存。 rootThread 获得一个指向 threadData 的指针。所以用它作为 pthread* b = d->ths 进一步 pthread_create 想要一个指向 pthread_t 的指针,因此不要取消它。

标签: c struct pthreads dereference


【解决方案1】:

看起来(例如)您没有分配。你必须这样做:

void* Thread(void* theCUstom);

pthread_t* threadHandle = malloc(sizeof(pthread_t));
pthread_mutex_t mutex; // mutex lock
pthread_attr_t attr;   // thread attributes
pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&attr);
unsigned long errRes = pthread_create(threadHandle, &attr, Thread, yourCustom);

【讨论】:

    【解决方案2】:

    您无法维护以这种方式使用 pthread_t 的索引。每次重新输入 rootThread() 时,b+1 都会保持不变。您可能需要在 threadData 中有一个单独的索引变量,或者需要一个可以遍历列表的第二个指针。要么这样,要么不要创建临时变量 pthread_t *b。

    typedef struct threadData {
        pthread_t *ths;
        int thsIdx;
    } threadData;
    
    void *rootThread(threadData *d) {
        pthread_create( &d->ths[d->thsIdx++],NULL,someRandomFunction,NULL);
    }
    

    或者你的方式:

     void *rootThread(threadData *d) {
        pthread_create( d->ths, NULL, someRandomFunction, NULL);
        ++d->ths; // this is nasty because you lose the pointer to the beginning of the array.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2010-09-15
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 2013-11-05
      • 2017-01-13
      相关资源
      最近更新 更多