[問題] pthread及參數為指標的問題

作者: 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):
抱歉對指標的概念不是很好,還請前輩們多多賜教,感謝萬分
作者: descent (「雄辯是銀,沉默是金」)   2018-10-11 17:25:00
你的 func() 怎麼自己又要 create thread?是 Partition 嗎?
作者: Ryspon (Ry)   2018-10-11 17:35:00
int p = (int) arg[0]
作者: achicn3 (Sher)   2018-10-11 18:13:00
int p,q;改intptr_t型態
作者: joe820730 (Let it go)   2018-10-11 19:41:00
https://ideone.com/tQloW0在thread裡面建一個變數把轉型後的指標存起來
作者: Ryspon (Ry)   2018-10-11 20:20:00
void * 算是一個通用型態的概念,用來傳遞各種型態的參數,傳進去之後要自己轉型成需要的 type ,把 arg 轉型後 assign 給你想要的 type pointer ,就像前幾樓回覆的範例那樣
作者: Paravion (ElonMusk)   2018-11-01 19:07:00
是作業系統的merge sort作業嗎

Links booklink

Contact Us: admin [ a t ] ucptt.com