pthread_create 报函数参数不匹配问题

本文介绍了如何正确使用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 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值