2012-07-03 77 views
1

請在下面看到我的僞代碼。代碼註釋應該解釋我的問題。我對C中的pthread和鏈表都很陌生,所以我已經深入了一下。我只需要在thread_work函數中輸出str的值。順序的代碼位很好,但是當每個線程完成它的工作時,它不能打印出str的值。正確地將鏈表節點傳遞給pthread函數

// linked list definition 
struct linked_list { 
    char *str; 
    struct linked_list *next; 
}; 

// linked list initiation 
struct linked_list *root; 
struct linked_list *next_info; 
root = malloc(sizeof(struct linked_list)); 

// main code 
some loop { 
    next_node->str = str; 
    printf("%s\n", next_node); // PRINTS FINE 
    pthread_t thread; 
    rc = pthread_create(&thread, NULL, thread_work, (void *) &next_node); 
    next_node->next = malloc(sizeof(struct linked_list)); 
    next_node = next_node->next; 
} 

// code executed by each thread 
void *thread_work(void *thread_arg) { 
    struct linked_list *ll; 
    ll = (struct linked_list *)thread_arg; 
    printf("%s\n", ll->str); // PRINTS SOME MESS (��E#) 
} 

在我實際的代碼有該linked_liststruct的幾個成員。

非常感謝。

+1

剛一說明:由於'thread_arg'是'無效*',但絕對沒有必要轉換爲另一種數據指針類型時施放。只要做到這一點:'struct linked_list * ll = thread_arg;''。 – unwind

回答

2

你有一個指針類型不匹配:你傳遞一個指針的指針列表節點,但裏面thread_work你把它當作一個指向節點。無論是在通話next_node之前刪除符號,以pthread_create,或者改變你thread_work如下:

void *thread_work(void *thread_arg) { 
    struct linked_list **llp, *ll; 
    llp = (struct linked_list **)thread_arg; 
    ll = *llp; 
    printf("%s\n", ll->str); // PRINTS SOME GOOD STUFF 
} 
+0

謝謝。我會將此標記爲已解決,然後最短時間已過期。 – ale

0

如果printf("%s\n", next_node)做工精細,next_node是一個指針,爲此你在pthread_create schouldn't指向指針()next_node的 定義將是不錯的;)

嘗試rc = pthread_create(&thread, NULL, thread_work, (void *) next_node);

0

此代碼是壞:

// main code 
some loop { 
    next_node->str = str; 
    printf("%s\n", next_node); // PRINTS FINE 
    pthread_t thread; 
    rc = pthread_create(&thread, NULL, thread_work, (void *) &next_node); 
    next_node->next = malloc(sizeof(struct linked_list)); 
    next_node = next_node->next; 
} 

這裏的問題是,你是一個指針傳遞給它的立即值變化的變量致電pthread_create後。因爲它需要一些時間操作系統的過程中克隆到一個新的線程,在執行next_node = next_node->next;聲明後的實際thread_work可能(在大多數情況下會)開始,並挑選的next_node錯誤值。你應該通過價值next_node,而不是它的地址:

// main code 
some loop { 
    next_node->str = str; 
    printf("%s\n", next_node->str); // PRINTS FINE 
    pthread_t thread; 
    rc = pthread_create(&thread, NULL, thread_work, (void *) next_node); 
    // Store this thread handle somewhere safe to be able to join the thread later on 
    next_node->next = malloc(sizeof(struct linked_list)); 
    next_node->next->str = next_node->next->next = NULL; // Always a good idea 
    next_node = next_node->next; 
} 
相關問題