【发布时间】:2023-01-25 21:22:10
【问题描述】:
我有一个主文件,我计划在其中启动我的 C++ 程序的线程,现在,我只想启动并运行其中一个线程,然后再转到其他线程,但事实证明这很困难。线程的目的是让 TCP 服务器和客户端同时运行,我已经测试了我的 TCP 代码并且它有效,现在的问题是在各自的线程中运行每个线程。下面显示了我的 main.cpp 代码:
#include <thread>
#include <iostream>
#include <functional>
#include "./hdr/tcpip_server.hpp"
#include "./hdr/tcpip_client.hpp"
using namespace std;
tcpServer *backendServer;
//This is done because the callback function of std::thread tcpip_server_thread complains when I only use 'backendServer->Monitor' as my callback function
void StartThread (void) {backendServer->Monitor();}
int main (void)
{
/*Initiate and start TCP server thread*/
std::thread tcpip_server_thread; // done to define object to be used outside the scope of the if statement below
if (backendServer->Init())
{
std::thread tcpip_server_thread (StartThread);
}
/*Initiate and start data reader thread*/
//std::thread tcpip_client_thread (tcpip_client);
tcpip_server_thread.join();
//tcpip_client_thread.join();
return 0;
}
后端服务器类如下:
class tcpServer
{
private:
int listening;
sockaddr_in hint;
sockaddr_in client;
socklen_t clientSize;
int clientSocket;
char host[NI_MAXHOST];
char service[NI_MAXSERV];
char buf[4096];
public:
bool Init ();
void Monitor ();
};
我在这段代码中得到的唯一错误是标题中的错误,我只在代码执行时得到它,编译代码时没有收到错误。
尝试以下操作时:
std::thread tcpip_server_thread (backendServer->Monitor);
我收到以下警告:
a pointer to a bound function may only be used to call the function
和
no instance of constructor "std::thread::thread" matches the argument list
任何帮助将不胜感激,因为这是我的第一个实施线程的项目。
【问题讨论】:
-
这是一个问题范围,一生和变量阴影.简而言之:您在不同范围内有两个截然不同且独立的变量,都命名为
tcpip_server_thread。无法加入其中一个对象。 -
请发布minimal reproducible example。
tcpServer *backendServer;没有指向任何地方,您发布的代码中没有任何内容改变了这一点。然后这个backendServer->Monitor();或这个backendServer->Monitor变得 boooooom -
@Someprogrammerdude 我认为代码还不够重要。
backendServer从未设置为指向任何内容,因此当StartThread()取消引用NULL指针时代码失败。 -
当你想要一个对象时,你应该使用一个对象。指针只是指向,它们并没有比这更多。
-
感谢@Some programmer dude 的回复我只是想确保我明白你说的是删除只有
std::thread tcpip_server_thread;的代码行吗?然后将 ,join 移动到 if 语句内的代码范围内?
标签: c++ multithreading