gpt4 book ai didi

c++ - 在 C++ 中创建线程时出错

转载 作者:行者123 更新时间:2023-11-30 04:08:35 25 4
gpt4 key购买 nike

我正在执行一个发送短信程序,但是当我在线程中创建与服务器的连接时出现错误。

g++ -L/usr/lib/i386-linux-gnu -o main Socket.cpp ServerSocket.cpp modemSMS_w.cpp main.cpp Config.cpp -lpthread -lserial -lxml2 -lmysqlclient
modemSMS_w.cpp: In member function ‘void modem::enviasms()’:
modemSMS_w.cpp:96:77: error: cannot convert ‘void* (modem::*)(void*)’ to ‘void* (*)(void*)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’

程序:

#include "modemSMS_w.hpp"
#define CTRL_C "\x1A"

using namespace LibSerial;
using namespace std;

modem::modem()
{
}

void *modem::func_servidor(void *ptr)
{

ServerSocket server(30001);

try {
ServerSocket new_sock;
while(1)
{
server.accept(new_sock);
cout << "Conexao aceita" << endl;
}
}
catch (SocketException& e) {
cout << "Erro: Criando Servidor" << endl;
}

}

int modem::setSerial() {
.....
....
...
}

void modem::enviasms(){

pthread_t thread_servidor;
pthread_cond_t cv;

const int PORT_MON = 30000;
string serialPort = "/dev/ttyS0";

int argc;
int ret;
char **argv;

cout << "\n------------------------\n MODEM GPRS \n------------------------" << endl;
string mensagem ="Conversao";
mensagem.c_str();

ret = pthread_cond_init(&cv, NULL);
bool envia = true;
envia = true;
if (ret != 0)
{
cout << "Erro na criação do evento. Por favor reeinicie o programa." << endl;
}

//ERROR IN THIS LINE
pthread_create(&thread_servidor, NULL,&modem::func_servidor, (void* ) true );

Config config;
SerialStream ssStream;
setSerial();

....
...
}

抱歉,我对在 C++ 中创建线程几乎一无所知。已经尝试解决这个问题,但没有成功。

最佳答案

您可以向您的类添加一个静态函数并在 pthread_create 函数中使用它:

class modem {
public:
//...
static void* thread_func(void* arg);
//...
};

void* modem::thread_func(void* arg) {
return reinterpret_cast<modem*>(arg)->func_servidor();
}

void *modem::func_servidor() {
// some code
}

void modem::enviasms(){
//some code scipped
if(pthread_create(&thread_servidor, NULL, &modem::thread_func, reinterpret_cast<void*>(this)) != 0) {
//some error handling code
}
//...
if(pthread_join(thread_servidor, NULL) != 0) {
// handle error
}
}

但是,恕我直言,使用 boost 或 std 线程要好得多。这种方法不需要静态函数:

auto thr = std::thread{ &modem::func_servidor, this };
//...
thr.join();

但是请注意,当线程存在时,您必须检查 this 指向的对象是否存在。

关于c++ - 在 C++ 中创建线程时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21726433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com