Winsock阻止套接字,多线程死锁 [英] Winsock blocking sockets, multithreading deadlock

查看:104
本文介绍了Winsock阻止套接字,多线程死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用此复制器在我的一些代码中找到了死锁:

I have tracked down a deadlock in some code of mine using this reproducer:

if( isClient )
{
    Sender sender;
    Receiver receiver;
    ConnectionPtr connection = Connection::create( description );
    TEST( connection->connect( ));

    receiver.start();
    Sleep( 100 );
    sender.start();

    sender.join();
}
else
{
    ConnectionPtr connection = Connection::create( description );
    TEST( connection->listen( ));

    Sender sender;
    Receiver receiver;
    ConnectionPtr reader = connection->accept();

    receiver.start();
    Sleep( 100 );
    sender.start();

    receiver.join();
}

我在同一台计算机上启动服务器,然后在127.0.0.1:1234上启动客户端进程.两者都立即在:: recv和:: send中死锁.发送方和接收方是在循环中执行发送/接收的独立线程.套接字是阻塞的BSD样式的TCP套接字.

I start on the same machine a server and then a client process on 127.0.0.1:1234. Both deadlock immediately in ::recv and ::send. Sender and Receiver are separate threads executing send/recv in a loop. The sockets are blocking, BSD-style TCP sockets.

当我更改操作顺序以在接收方之前启动发件人时,它会起作用.

When I change the order of operations to start the Sender before the Receivers, it works.

为什么?

推荐答案

在您的示例中,如果peer1不读取数据,则在套接字发送缓冲区已满后,peer2将阻止发送.

In your example if peer1 is not reading data a peer2 will block in send after socket send buffer is full.

如果您使用某种协议,并且客户端在等待响应时服务器无法读取消息部分,通常会发生死锁.

Usually deadlock can occur if you have some kind of a protocol and server fails to read message part while client is waiting for response.

通常为调试此类问题,在客户端和服务器端都引入了详细的日志记录.并且当问题发生时,您可以分析日志并查看出了什么问题.

Generally to debug this kind of problems verbose logging is introduced both on client and server sides. And when the problem occurs you can analyze logs and see what went wrong.

这篇关于Winsock阻止套接字,多线程死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆