[問題] pthread及參數為指標的問題
開發平台(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):
抱歉對指標的概念不是很好,還請前輩們多多賜教,感謝萬分
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.229.214.58
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1539235025.A.C96.html
※ 編輯: skyHuan (36.229.214.58), 10/11/2018 13:17:56
→
10/11 17:25,
5年前
, 1F
10/11 17:25, 1F
→
10/11 17:25,
5年前
, 2F
10/11 17:25, 2F
其實func()原本是Quicksort
我把跟問題沒關係的地方省略了
Partition函式用來找divide的地方的
找到之後create thread分兩部分Quicksort
推
10/11 17:35,
5年前
, 3F
10/11 17:35, 3F
所以是型別轉換的問題嗎
我試了呼叫時func((void*)args);
呼叫完轉(int)好像都有點怪怪的
不確定是不是要像argc argv那樣
函式參數的定義要改才能直接用
void* func(void *arg[]) { }
可是這樣呼叫函式前要設定的參數
int args[2] = { p, r }; 我就不知道要怎麼改了
不好意思指標的觀念沒有很清楚弄得很混亂><
※ 編輯: skyHuan (223.137.198.187), 10/11/2018 18:02:35
※ 編輯: skyHuan (223.137.198.187), 10/11/2018 18:04:21
推
10/11 18:13,
5年前
, 4F
10/11 18:13, 4F
→
10/11 19:41,
5年前
, 5F
10/11 19:41, 5F
→
10/11 19:42,
5年前
, 6F
10/11 19:42, 6F
推
10/11 20:20,
5年前
, 7F
10/11 20:20, 7F
→
10/11 20:20,
5年前
, 8F
10/11 20:20, 8F
→
10/11 20:20,
5年前
, 9F
10/11 20:20, 9F
→
10/11 20:20,
5年前
, 10F
10/11 20:20, 10F
謝謝樓上的各位!
我建一個新變數存起來型別轉換好後就可以了
感謝萬分
※ 編輯: skyHuan (223.137.198.187), 10/11/2018 23:19:33
推
11/01 19:07,
5年前
, 11F
11/01 19:07, 11F
推
03/13 02:15,
6年前
, 12F
03/13 02:15, 12F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):