• 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
    ", 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
    ", 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 }
  • 相关阅读:
    java抽象类
    java不支持多继承
    logback颜色
    @ConfigurationProperties、@Value、@PropertySource
    redis命令
    mac下安装rabbitmq
    mac下安装jmeter
    python TypeError: 'int' object is not callable 问题解决
    白炽灯串联发光问题_高中知识(原创)
    python 离散序列 样本数伸缩(原创)
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/7198544.html
Copyright © 2020-2023  润新知