2013-02-24 104 views
1

我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元素。請幫忙!

謝謝,:)。

+0

你如何分配你的struct treadData?目前,您似乎創建線程數據的成員ths只是作爲一個指針,沒有爲它分配內存。 rootThread獲取一個指向threadData的指針。所以使用它作爲pthread * b = d->進一步的pthread_create需要一個指向pthread_t的指針,因此不要使其不合適。 – hetepeperfan 2013-02-24 22:36:07

回答

0

您無法維護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. 
} 
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);