[英]C++ Implementing threads with Inter thread communication
我目前正在尝试使用主程序创建使用Winsock的服务器和客户端应用程序,我需要有第二个线程来始终监听数据。
这种通信是非阻塞的。 我确实很难找到线程之间进行通信的方式,我正在寻找的一个示例是:服务器向客户端发送一个字符串,例如“ viewData”,此类信息将由主线程获取,然后再由特定线程获取。函数也可以被调用。
这是我的线程的示例,我正在使用_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();
}
我还看到了该站点,它可以为ITC提供帮助,有关此的任何建议-> http://derkarl.org/itc/
通过一个简单的主循环,我对可能有效的任何方法都感兴趣,我已经尝试了好几天,但没有任何运气,非常感谢您的帮助。
您可以具有一个共享变量(带有锁),并且两个线程都轮询/写入该变量,或者可以在线程之间注册回调函数 ,并在发生某个事件时调用另一个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.