[問題] 關於pthread...

看板C_and_CPP (C/C++)作者 (從零開始是如此困難)時間15年前 (2010/11/20 17:18), 編輯推噓2(2015)
留言17則, 4人參與, 最新討論串1/3 (看更多)
因為我現在正在研究同步程式的寫法 所以我從這個版上的某一個大大的 文章裡把範例程式碼copy到我的visual studio 2010 #include<stdio.h> #include<pthread.h> #include<stdlib.h> #include<time.h> #include<windows.h> void *print_message_function_1( void *ptr1); void *print_message_function_2( void *ptr2); int main(void) { pthread_t thread1,thread2; char *message1="睡一秒"; char *message2="睡兩秒"; int i; pthread_create( &thread1, NULL, &print_message_function_1, (void*) mes\ sage1); pthread_create( &thread2, NULL, &print_message_function_2, (void*) mes\ sage2); pthread_join( thread1, NULL); pthread_join( thread2, NULL); } void *print_message_function_1( void *ptr1) { int k; char *message; message = (char *) ptr1; for(k=1;k<=10;k++) { printf("%s\n",message); _sleep(1); } } void *print_message_function_2( void *ptr2) { int j; char *message; message = (char *) ptr2; for(j=1;j<=10;j++) { printf("%s\n",message); _sleep(2); } } 我想請問的問題是 這段code每次compile的時候 一定都會出錯 錯誤訊息如下 1>d:\my documents\visual studio 2010\projects\test\test\test.cpp(36): error C4716: 'print_message_function_1' : 必須傳回值 1>d:\my documents\visual studio 2010\projects\test\test\test.cpp(49): error C4716: 'print_message_function_2' : 必須傳回值 可是問題在於這兩個函式的回傳值不是宣告成void嗎? 根據小弟微薄的c++知識 應該是不用回傳的 我抓不出到底這個問題為什麼會出現 希望板上的大大可以給予協助 (ps.不只上面這個code有這問題 我只要去找pthread的教學code都有這問題) 我算是越等使用這個函式 所以有很多不明白的地方 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.101.195

11/20 17:19, , 1F
void跟void *是兩回事 至少要回傳個 NULL
11/20 17:19, 1F

11/20 17:20, , 2F
你是說 pthread_exit(NULL); 嗎
11/20 17:20, 2F

11/20 17:21, , 3F
在你 function 最後面加個 return NULL;
11/20 17:21, 3F

11/20 17:21, , 4F
不過你講的應該也可以
11/20 17:21, 4F

11/20 17:22, , 5F
void *print_message_function_1( void *ptr1); 原型宣告
11/20 17:22, 5F

11/20 17:22, , 6F
我加了 pthread_exit(NULL); 坦白說也是一樣 不清楚原因
11/20 17:22, 6F

11/20 17:23, , 7F
那 return NULL; 應該可以解決你的問題了
11/20 17:23, 7F

11/20 17:25, , 8F
你以為回傳值是void,事實上是 void *,由原型宣告決定
11/20 17:25, 8F

11/20 17:26, , 9F
加了以後確實能解決上述問題 但是新問題又來了@@
11/20 17:26, 9F

11/20 17:26, , 10F
好特別喔 XD
11/20 17:26, 10F
1>test.obj : error LNK2019: 無法解析的外部符號 __imp__pthread_join 在函式 _main 中被參考 1>test.obj : error LNK2019: 無法解析的外部符號 __imp__pthread_create 在函式 _main 中被參考 抱歉 這方面基礎甚差 不得已跳等使用 ※ 編輯: f202097 來自: 140.116.101.195 (11/20 17:28)

11/20 17:29, , 11F
果然是 link error... 你沒把 pthread 安裝好
11/20 17:29, 11F

11/20 17:29, , 12F
不然就是 visual studio 的路徑沒設定好
11/20 17:29, 12F

11/20 17:30, , 13F
我還在想說 windows 上能直接拿來寫是哪招
11/20 17:30, 13F

11/20 17:30, , 14F
被抓到問題了 我當初是不得其門而入 所以僅僅複製貼上
11/20 17:30, 14F

11/20 17:33, , 15F
所以解決囉?
11/20 17:33, 15F

11/20 17:36, , 16F
另打一篇中
11/20 17:36, 16F

11/20 17:44, , 17F
算解決大部分問題 謝謝
11/20 17:44, 17F
文章代碼(AID): #1Cvv9Frn (C_and_CPP)
文章代碼(AID): #1Cvv9Frn (C_and_CPP)