pthread_create 報函數參數不匹配問題


pthread_create方法遇到類方法時總會報  argument of type ‘void* (Thread::)(void*)’ does not match ‘void* (*)(void*)’
pthread_create方法第三個參數只能是C函數指針或者類到靜態函數指針。
下面記錄一下解決方法

 

 1 include <stdio.h>
 2 #include <pthread.h>
 3 #include <unistd.h>
 4 
 5 class Thread{
 6 public:
 7     Thread(int num = 5):_num(num){ }
 8 
 9     static void *work(void *args){  //靜態函數有訪問函數, 變量限制, 這里直接傳入類指針變量
10         Thread *handle = (Thread*)args;
11         for (int i = 0; i < handle->_num; ++i){
12             printf("sleep i = %d\n", i); 
13             sleep(1);
14         }   
15         pthread_exit(NULL);
16     }   
17 
18     int _num;
19 };
20 
21 void *inc_count(void *args){
22     for (int i = 0; i < 5; ++i){
23         printf("inc_count i = %d\n", i); 
24         sleep(1);
25     }   
26     pthread_exit(NULL);
27 }
28 
29 int main(){
30     Thread obj; 
31     pthread_t threads[2];
32 
33     pthread_create(&threads[0], NULL, inc_count, NULL);     //必須是C函數指針
34     pthread_create(&threads[1], NULL, Thread::work, &obj);  //或者時類靜態函數指針
35     obj._num = 10; 
36     
37     pthread_join(threads[0], NULL);
38     pthread_join(threads[1], NULL);
39     return 0;
40 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM