我有一个接受字符串的函数。由于 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: 错误:正在初始化 'int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)' 的参数 3 [ -f宽容]
最佳答案
pthread_create
期望的参数是,
void *(*)(void *)
这是一个指向接受空指针并返回空指针的函数的指针。
将您的方法更改为具有以下签名:
/*static*/ void* printString(void *x) { ... }
关于c++ - 使用接受 char 指针的函数调用 pthread_create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22912735/