zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    TransGAN
    Paper-About-GAN (3)
    VAE的Pytorch实现
    Lua_元表
    Kong网关1_service与route
    Win系统Notepad++中使用Json、xml格式化插件
    Linux下Konga的安装
    Linux下设置pgsql远程访问
    Linux中查看端口占用情况
    Mysql使用存储过程插入十万条数据
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/7198544.html
Copyright © 2011-2022 走看看