解引用一个结构内的阵列正在使用ptread_create
问题描述:
我ThreadData结构:解引用一个结构内的阵列正在使用ptread_create
typedef struct threadData {
pthread_t *ths;
} threadData;
其中*是部份的pthread_t
阵列。
现在,我创建的动作,使用下面的函数,它创建的部份[1]
void *rootThread(threadData *d) {
pthread_t *b = (*d).ths;
pthread_create(*(b+1),NULL,someRandomFunction,NULL);
}
但是,这似乎并没有工作,一个新的线程的线程。
我不确定我是否很好地解引用了pthread_t元素。请帮忙!
谢谢,:)。
答
您无法维护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.
}
答
它看起来像(例如)你不分配。你必须这样做:
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);
你如何分配你的struct treadData?目前,您似乎创建线程数据的成员ths只是作为一个指针,没有为它分配内存。 rootThread获取一个指向threadData的指针。所以使用它作为pthread * b = d->进一步的pthread_create需要一个指向pthread_t的指针,因此不要使其不合适。 – hetepeperfan 2013-02-24 22:36:07