【问题标题】:calling pthread_create with a function which takes char pointer使用带有 char 指针的函数调用 pthread_create
【发布时间】:2014-05-19 17:09:16
【问题描述】:

我有一个接受字符串的函数。由于 pthread 不接受 string ,因此我将函数的参数设置为 char 指针。现在我想用 pthread_create 调用该函数,但我做不到。我认为由于 void * 而出现问题。我搜索了它并进行了一些铸造,但我无法成功。我该如何修复它以便它可以在 g++ 下工作

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

void printString(char *x)
{
    cout << x << endl;
        pthread_exit(NULL);
}

int main ()
{
     pthread_t threads[NUM_THREADS];
     int rc;
     int i;
     string temp = "hello";

  char *bufferG;
  bufferG = new char[temp.size() + 1]; 
  std::copy(temp.begin(), temp.end(), bufferG); 
  bufferG[temp.size()] = '\0'; 

     for( i=0; i < NUM_THREADS; i++ ){
         cout << "main() : creating thread, " << i << endl;
         rc = pthread_create(&threads[i], NULL, printString,  &bufferG ); //(void *) &bufferG also doesn't work
     }
 pthread_exit(NULL);
 }

错误是: thread.cpp:在函数“int main()”中: thread.cpp:27:69:错误:从“void ()(char)”到“void* ()(void)”的无效转换 [-fpermissive] /usr/include/pthread.h:225:12: 错误:初始化参数 3'int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)' [ -fpermissive]

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    pthread_create 期望的参数是,

    void *(*)(void *)
    

    这是一个指向函数的指针,它接受一个 void 指针并返回一个 void 指针

    将您的方法更改为具有以下签名:

    /*static*/ void* printString(void *x) { ... }
    

    【讨论】:

    • 无论cout 都可以编译但不能打印“hello”
    • @user1308990 不要在pthread_create 中传递&amp;bufferG,而是传递bufferG
    【解决方案2】:

    好的,试试这个,现在主线程加入子线程执行,而不是在线程 fn 中打印单个字符,我们现在使用整个缓冲区来代替

    #include <iostream>
    #include <cstdlib>
    #include <pthread.h>
    
    using namespace std;
    
    #define NUM_THREADS     5
    
    void * printString(void *x)
    {
        cout << ((char *)x)<< endl;
    }
    
    int main ()
    {
         pthread_t threads[NUM_THREADS];
         int rc;
         int i;
         string temp = "hello";
    
      char *bufferG;
      bufferG = new char[temp.size() + 1]; 
      std::copy(temp.begin(), temp.end(), bufferG); 
      bufferG[temp.size()] = '\0'; 
    
    
         for( i=0; i < NUM_THREADS; i++ ){
             cout << "main() : creating thread, " << i << endl;
             rc = pthread_create(&threads[i], NULL, printString,  bufferG ); 
         }
        for( i=0; i < NUM_THREADS; i++ ){
         pthread_join(threads[i], NULL);
        }
     pthread_exit(NULL);
     }
    

    【讨论】:

    • 可以编译但不能打印“HELLO”
    • @user1308990,现在尝试编辑后的分析器,应该可以正常工作
    • @user1308990,如果答案可以接受,请接受我的两分钱
    • 不能同时接受两个答案,因为@mockinterface先回答,这对他来说是不公平的
    猜你喜欢
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多