作者:
skyHuan (Huan)
2018-10-11 13:17:03開發平台(Platform): (Ex: Win10, Linux, ...)
Linux
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
pthread
問題(Question):
最近在做多執行緒的實作遇到兩個問題
1.
因為pthread_create要呼叫的函式需要的參數是用指標宣告
所以函式的參數宣告成(void *)
我用一個args array傳入參數
那這個參數在函式中該怎麼取用呢
我寫的直接用arg[0], arg[1]應該是錯的
compiler會有dereferencing "void *" pointer的warning
2.
另外最後我想要divide成兩個部份給兩個執行緒去執行
呼叫的pthread_create的第三個&第四個參數
直接給函式名字&新的存參數array這樣是對的嗎
錯誤結果(Wrong Output):
dereferencing "void *" pointer的warning
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
int Partition(int p, int r) {
...
return q;
}
void* func(void *arg) {
pthread_attr_t attr;
pthread_t thread_L;
pthread_t thread_R;
pthread_attr_init(&attr);
int p = arg[0];
int r = arg[1];
if (p < r) {
int q = Partition(p, r);
int arg_L[2] = { p, q-1 };
int arg_R[2] = { q+1, r };
//QuickSort(arg_L);
if(pthread_create(&thread_L, NULL, func, arg_L)) {
fprintf(stderr, "error an exit\n");
return NULL;
}
//QuickSort(arg_R);
if(pthread_create(&thread_R, NULL, func, arg_R)) {
fprintf(stderr, "error an exit\n");
return NULL;
}
pthread_join(thread_L, NULL);
pthread_join(thread_R, NULL);
}
}
int main(int argc, char *argv[]) {
...
int args[2] = { p, r };
func(args);
}
補充說明(Supplement):
抱歉對指標的概念不是很好,還請前輩們多多賜教,感謝萬分