duangutang3940 2016-07-25 10:44
浏览 213
已采纳

Golang net.Conn并行写入

I have multiple Goroutines sharing a net.Conn object. Can they issue a Write calls simultaneously?

My main concern is that of Write calls which are partially done. Say I intend to wrote 100 bytes, but only 30 were sent, so I need to send 70 more. For this I will typically write a loop:

count := 0
for count < len(buf) {
    byteSent, err := conn.Write(buf[count:])
    //check error 

    count += byteSent
}

But I see that Go implements this loop in net.Conn.Write line number 318 and it does so by taking a lock.

However, on Windows implementation there is no such loop except that there is a call to WSASend. I do not know how WSASend behaves and could not get much from the MSDN docs

Hence the questions are:

[edit] Added 4th question

  1. Do I need to acquire a lock everytime I write to socket?
  2. If yes, then the purpose of acquiring the lock in Write implementation is defeated.
  3. In unix implementation, does it mean that I cannot get byteSent < len(buf) unless err != nil? (I mean am I reading the code correct?)
  4. Does the WSASend on Windows implements the equivalent loop in Unix implementation
  • 写回答

2条回答 默认 最新

  • dqzow3859 2016-07-26 11:29
    关注
    1. The io.Write says that in case of partial write, err will be != nil

    2. Found here on StackOverflow that WSASend need not have a loop around it.

    3. From #1 & #2, it implies that I need not acquire lock before calling net.Conn.Write.

    So my question stands answered.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵
  • ¥15 cfx离心泵非稳态计算