简体   繁体   中英

pthread_create with no arguments?

I want to create a thread with no function arguments but I keep getting errors that are seriously bugging me because I cant get something super simple to work right

Heres my code:

#include<stdio.h>
#include<array>
#include<pthread.h>
#include<fstream>
#include<string>

void *showart(NULL);

int main(int argc,  char** argv){
    pthread_t thread1;
    pthread_create( &thread1, NULL, showart, NULL);
    getchar();
    return 0;
}

void *showart(NULL)
{
    std::string text;
    std::ifstream ifs("ascii");
    while(!ifs.eof()) 
    {
      std::getline(ifs,text);
      printf(text.c_str());
    }
}

It gives the error:

main.cpp:11:50: error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’ [-fpermissive]

Your function has to match the pthread one. Meaning it needs to take and return a void* . Use void* showart(void*); instead.

Both the declaration and definition for your thread function are incorrect. You can use NULL when calling it, but the type of that parameter, needed for declaration/definition, is void * .

Hence you need something like:

void *showart(void *);              // declaration
void *showart(void *unused) { ... } // definition

In other words, this will do the trick:

#include<stdio.h>
#include<array>
#include<pthread.h>
#include<fstream>
#include<string>

void *showart (void *);

int main (int argc,  char **argv) {
    pthread_t thread1;
    pthread_create (&thread1, NULL, showart, NULL);
    getchar();
    return 0;
}

void *showart (void *unused) {
    std::string text;
    std::ifstream ifs("ascii");
    while(!ifs.eof()) {
        std::getline (ifs, text);
        printf ("%s\n", text.c_str());
    }
}

Although you should probably consider making your code a little more robust, such as checking the return code from pthread_create() , joining to the thread within main() , checking to ensure the file exists, and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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