简体   繁体   English

pthread c ++从void *(*)到void *(*)(void *)的无效对话

[英]pthread c++ invalid conversation from void * (*) to void* (*)(void*)

I'm new in C++ and trying to create multiple threads with pthread . 我是C++新手,并尝试使用pthread创建多个线程。

typedef struct thread_args{
    int &sockfd;
    struct sockaddr_in &serv_addr;
    int size_serv_addr;
    socklen_t &clilen;
    int &newsockfd;
};

void create_server(int &sockfd, struct sockaddr_in &serv_addr, int size_serv_addr, socklen_t &clilen, int &newsockfd){
}

int main(int argc, char *argv[])
{
     int sockfd, newsockfd;
     socklen_t clilen;

     pthread_t t1;
     struct sockaddr_in serv_addr, cli_addr;
     struct thread_args *args;
     args->clilen = clilen;
     args->newsockfd = newsockfd;
     args->serv_addr = serv_addr;
     args->size_serv_addr = sizeof(serv_addr);
     args->sockfd = sockfd;


     pthread_create(&t1, NULL, create_server, &args);
     printf("hello abc");
     return 0; 
}

When I run this code, it has a message: 当我运行此代码时,它会显示一条消息:

error:/bin/sh -c 'make -j 4 -e -f   error: invalid conversion from 'void* (*)(int&, sockaddr_in&, int, socklen_t&, int&) {aka void* (*)(int&, sockaddr_in&, int, unsigned int&, int&)}' to 'void* (*)(void*)' [-fpermissive]
      pthread_create(&t1, NULL, create_server, &args);

How can I fix this? 我怎样才能解决这个问题?

Signature for your thread function should be: 您的线程函数的签名应为:

void *(*start_routine) (void *)

but you provide: 但您提供:

void create_server(int &sockfd, struct sockaddr_in &serv_addr, int size_serv_addr, socklen_t &clilen, int &newsockfd)

you should create a function like: 您应该创建一个类似以下的函数:

void* myThread(void *arg);

then args argument in pthread_create call will be passed as arg parameter to myThread , you can use its fields to call create_server 然后pthread_create调用中的args参数将作为arg参数传递给myThread ,您可以使用其字段来调用create_server

Your function definition does not match the type pthread_create wants to have. 您的函数定义与pthread_create想要的类型不匹配。 It requires only 1 arguments and that is a void* (so a function void function(void* args) ). 它仅需要1个参数,并且是void* (因此是一个函数void function(void* args) )。

you need to change create_server to 您需要将create_server更改为

void create_server(void* voidArgs) {
    thread_args* args = static_cast<thread_args*>(voidArgs);
    //...
}

You will not have those issues though if you use the c++11 std::thread object. 但是,如果使用c ++ 11 std :: thread对象,则不会有这些问题。 There you can directly use the argument type and with any number of arguments you like. 在那里,您可以直接使用参数类型以及任意数量的参数。 So you don't have to define the thread_args struct. 因此,您不必定义thread_args结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM