[英]C++ Implementing threads with Inter thread communication
im currently attempting to create server and client application that use winsock, with a main program I need to have a second thread to always be listening for data. 我目前正在尝试使用主程序创建使用Winsock的服务器和客户端应用程序,我需要有第二个线程来始终监听数据。
This communication is non blocking. 这种通信是非阻塞的。 I am really having trouble in finding a way of communicating between threads, an example of what im looking for is: Server sends a string to the client eg "viewData" and this kind of information will be fetched by the main thread and then a specific function may also be called.
我确实很难找到线程之间进行通信的方式,我正在寻找的一个示例是:服务器向客户端发送一个字符串,例如“ viewData”,此类信息将由主线程获取,然后再由特定线程获取。函数也可以被调用。
Here is an example of my thread, i am creating this using _beginthread( (void(*)(void*))SocketReceive, 0, (void*)&ohuman );
这是我的线程的示例,我正在使用
_beginthread( (void(*)(void*))SocketReceive, 0, (void*)&ohuman );
创建此线程_beginthread( (void(*)(void*))SocketReceive, 0, (void*)&ohuman );
//thread focused on listening to connection
void SocketReceive( comms* ohuman)
{
char buffer[1000];
int inDataLength;
std::string contents;
for(;;)
{
if(!ohuman->getGameOn())
{
// Display message from server
memset(buffer,0,999);
inDataLength=recv((INT_PTR)ohuman->getSocket(),buffer,1000,0);
contents = std::string(buffer); //create a string from the char array for easy access
//only display if we get some content
if(inDataLength > 0)
{
//???DealWithMessage(
int nError=WSAGetLastError();
if(nError!=WSAEWOULDBLOCK&&nError!=0)
{
std::cout<<"Winsock error code: "<<nError<<"\r\n";
std::cout<<"Server disconnected!\r\n";
// Shutdown our socket
shutdown((INT_PTR)ohuman->getSocket(),0x01);
// Close our socket entirely
closesocket((INT_PTR)ohuman->getSocket());
break;
}
}
}
_endthread();
}
I also saw this site which is supposed to help out with ITC, any advice on this-> http://derkarl.org/itc/ 我还看到了该站点,它可以为ITC提供帮助,有关此的任何建议-> http://derkarl.org/itc/
With a straightforward main loop, I am interested in any approach that might work, I've been trying to figure this out for a couple of days with no luck, any help is greatly appreciated. 通过一个简单的主循环,我对可能有效的任何方法都感兴趣,我已经尝试了好几天,但没有任何运气,非常感谢您的帮助。
您可以具有一个共享变量(带有锁),并且两个线程都轮询/写入该变量,或者可以在线程之间注册回调函数 ,并在发生某个事件时调用另一个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.