使用带有char指针的函数调用pthread_create

时间:2014-04-07 12:41:23

标签: c++ multithreading

我有一个带字符串的函数。由于pthread不接受字符串,我使用函数的参数char指针。现在我想用pthread_create调用该函数但我不能这样做。由于无效而出现问题*我认为。我搜索了它并进行了一些铸造,但我不能成功。我该如何修复它以便它可以在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:错误:初始化'int pthread_create的参数3(pthread_t *,const pthread_attr_t *,void *()(void ),void *)'[ -fpermissive]

2 个答案:

答案 0 :(得分:3)

pthread_create所期望的论点是,

void *(*)(void *)

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

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

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

答案 1 :(得分:1)

好的,试试这个,现在主线程连接子进行执行,而不是在线程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);
 }