請在下面看到我的僞代碼。代碼註釋應該解釋我的問題。我對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_list
struct
的幾個成員。
非常感謝。
剛一說明:由於'thread_arg'是'無效*',但絕對沒有必要轉換爲另一種數據指針類型時施放。只要做到這一點:'struct linked_list * ll = thread_arg;''。 – unwind