【问题标题】:pthread_create with no arguments?pthread_create 没有参数?
【发布时间】:2015-10-18 01:15:35
【问题描述】:

我想创建一个没有函数参数的线程,但我不断收到严重困扰我的错误,因为我无法让一些超级简单的东西正常工作

这是我的代码:

#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());
    }
}

它给出了错误:

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

【问题讨论】:

    标签: c++ c++11 pthreads posix


    【解决方案1】:

    您的函数必须与 pthread 匹配。这意味着它需要获取并返回void*。请改用void* showart(void*);

    【讨论】:

      【解决方案2】:

      您的线程函数的声明和定义都不正确。您可以在调用它时使用NULL,但声明/定义所需的该参数的类型void *

      因此你需要这样的东西:

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

      换句话说,这可以解决问题:

      #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());
          }
      }
      

      尽管您可能应该考虑让您的代码更健壮一些,例如检查来自pthread_create() 的返回码、加入main() 中的线程、检查以确保文件存在等等。

      【讨论】:

      • 您不需要在定义中命名unused,这样可以避免在某些编译器配置下得到未使用的警告。
      猜你喜欢
      • 1970-01-01
      • 2011-12-18
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多