刨根問底系列(3)——關於socket api的原子操作性和線程安全性的探究和實驗測試(多線程同時send,write)
多個線程對同一socket同時進行send操作的結果
1. 概覽
1.1 起因
自己寫的項目里,為了保證連接不中斷,我起一個線程專門發送心跳包保持連接,那這個線程在send發送數據時,可能會與主線程中的send衝突,因此我就想探討一下socket api是否具有線程安全性。網上很多說法,但多是推測,於是我結合man pages、StackOverflow和大佬們的博客等資料,做了簡單的實驗測試一下,用事實說話。
1.2 探究的主要問題和結論預告
以下問題是主要關注Linux tcp,所有結論都是Linux環境下的, 但是也會有UDP, Windows C++,C++ boost庫和java語言等StackOverflow上相同問題下的資料和鏈接。
-
當兩個線程或進程同時對同一socket進行send(write)操作時,會不會出問題,例如兩個線程的內容會不會交錯, tcp和udp是否情況相同
- tcp情況下會有問題:當某線程發送的數據量過大時(實驗測試為一次性發送32KB),兩個線程發送的內容出現了交錯的情況;當數據量比較小時(測試為4B),內容沒有交錯。(我並沒有過多關注數據量大小的設置,總之可能出現交錯,所以盡量避免這樣使用)
- udp未測試,但是所有收集的資料都表示,在UDP情況下不存在這種問題
-
send或write是否線程安全
- 線程安全性:從實驗結果上看,不具備線程安全
關於socket的線程安全, 也有人認為是具備的,他們的意思是:可以一個線程發送,另一個線程同時接收,就叫線程安全,這個我是知道的,但是這與我想討論的情況不一樣,所以需要明確我說的socket線程安全的定義:兩個線程同時發送時的線程安全性。
1.3 文章組織
- 首先我會介紹實驗測試,包括測試思路,代碼(比較簡單),和測試結果
- 根據上述實驗結果的事實,去探究其問題出現的原因
- 關於原子性和其他一些觀點、平台、編程語言的探討分析
- 最後,會給一些建議和替代方案
2. 實驗測試
- 測試環境:VMware station 15,虛擬機Ubuntu server 18.04.4
- 測試代碼地址://github.com/whuwzp/linuxc/tree/master/bug/twothread_send
2.1 測試思路
測試思路很簡單,一端起兩個線程同時循環發送數據(一個線程發一串aaaa,另一個發一串bbbb),另一端接收並打印,看看結果會不會有交錯的。
關於內容交錯,我並不關心數據達到的順序,只關心一個大的數據包會不會穿插着另一個數據包,具體來說:兩個線程Ta,Tb,有一個socket S,Ta和Tb同時向S發送數據,其中Ta的要發送數據很大(需要分片),由Pa1和Pa2兩部分組成;Tb發送數據較小,為Pb1,那麼如果對端收到的是:
-
Pa1 Pa2 Pb1
或者Pb1 Pa1 Pa2
:則認為沒有交錯(Ta和Tb的數據各自都連續到達,只是順序未知而已) -
Pa1 Pb1 Pa2
:則認為有交錯。(因為Ta數據包被隔斷不連續了)
注意:測試時候某個線程發送的數據包一定要足夠大,否則不會出現交錯的現象,我之前就是發送太小,誤以為不會交錯,原因在第三節的分析中會講到。
2.2 測試代碼
測試代碼地址://github.com/whuwzp/linuxc/tree/master/bug/twothread_send
server.cpp, 以下簡要展示關鍵代碼:
typedef struct {//為了更好地展示,我發送的是結構體,用index標記是第幾個a或者b
char buf;
int index;
} myint;
//Ta
void * athread(void *) {
for (i = 0; i < 4 * 1000; i++) {
buf[i].buf = 'a';
buf[i].index = i;//標記是第多少個'a'
}
//循環發送, 每次發送4000個結構體數據
while (true) ret = write(fd_client, buf, 1000 * 4 * sizeof(myint));
}
//Tb
void *bthread(void *) {
for (i = 0; i < 100; i++) {
buf[i].buf = 'b';
buf[i].index = i;//標記是第多少個'b'
}
while (true) {
ret = 0;
for (int i = 0; i < 10; ++i) {//循環發送10次100個結構體
ret += write(fd_client, buf, 100*sizeof(myint));
}
sleep(1);
}
}
while (true) {
memset(buf, 0, 4 * 1000 * sizeof(myint));
ret = (int)read(fd_client, buf, 4 * 1000 * sizeof(myint));
for (i = 0; i < ret/sizeof(myint); i++) {
//因為4000個a打印起來很多,所以只打印b,或者接收數據不完全的情況
if (buf[i].buf == 'b' || ret != 4 * 1000 * sizeof(myint)) {
printf("ret=%d\n", ret);
for (i = 0; i < ret/sizeof(myint); i++){
printf("%c, %d\n", buf[i].buf, buf[i].index);//打印其索引
break;
}
}
}
}
運行:
./server
./client > result.txt
2.3 實驗結果
# 此處省略a0~a3391
a, 3389
a, 3390
a, 3391
# 此處是重點, 內容交錯的起點
b, 0
b, 1
# 此處省略b0~b99, 10次循環
b, 98
b, 99
a, 3392
a, 3393
# 此處省略a3394~a3999,以及b的後續
通過結果可以看出:
- 先接收了Ta發送的0~3391數據包
- 再接收Tb接收的10次0~100數據包
- 最後再又接收了Ta的3392~3999數據包
也就是說, Ta與Tb的數據包發生了交錯。
3. 原因探究和實驗結果分析
3.1 原子操作性和線程安全性
首先這兩個概念是有區別的(詳見stackoverflow上的討論):
- 原子性:意味着從一個操作開始的所有位元組一起結束,而不會與其他I / O操作交織(這是ibm文章摘自IEEE Std 1003.1-2001 System Interfaces volume中的定義)。也有的人說:要麼100%操作成功,要麼失敗了就把狀態回滾到操作之前,或者不可分割。百度百科-原子操作。
- 線程安全:多線程同時進行一個操作而不會相互影響。原子操作是實現線程安全的一種方式。(摘自stackoverflow上的討論
3.2 socket api是否線程安全與c/c++語言本身無關
socket不是c/c++語言標準, 所以它的線程安全依賴具體的實現. 每個系統不同, 有的系統實現socket時用了鎖來保護內部數據結構, 有的系統可能沒有, 所以得看系統具體實現.
Sockets are not part of C++ Standard so it depends on implementation. Generally they are not thread safe since send is not an atomic operation. Check this discussion for additional information.
EDIT: OS could have or couldn’t have internal lock for protecting internal structures. It depends on implementation. So you should not count on it.
摘自: //stackoverflow.com/questions/2354417/c-socket-api-is-thread-safe
3.3 可能原因分析
以下內容參考://quark.tistory.com/m/235 (這個鏈接不是原文章的鏈接,原文鏈接已經失效了,這個是韓國網站上轉載的),如果訪問慢,可以看我轉載的://www.cnblogs.com/whuwzp/articles/thread_safe.html。
簡單解釋一下:
- send函數最終調用內核的tcp_sendmsg()函數
- tcp_sendmsg()函數需要通過lock_sock()獲取一個鎖,然後開始循環分配緩衝區空間,並把待發送的數據拷貝過去,準備發送
- 如果待發送的數據特別大(這裡回答了為什麼發送32kb那麼大的數據)導致循環分配空間到某個階段失敗了(部分數據已經成功了),就會最終調用sk_stream_wait_memory()函數等待空間可用,而該函數內部會調用sk_wait_event()去釋放鎖,然後阻塞等待着
- 一旦這個線程釋放了鎖,那麼其他線程的send函數就可能通過lock_sock()競爭到鎖,然後發送他們的數據,這樣兩個線程的數據流就會交錯在一起了。
這個解釋非常符合實驗結果。但是這只是一種可能,我們只能判斷一定是釋放了鎖,且被別的線程競爭到了鎖,是不是只有內存分配失敗才會導致這樣呢?我也不太確定,希望讀者一起讀第四節,一起探討。
4. 其他的觀點探討和分析
4.1 原子性的問題
其實到現在我仍然不能確定send、write是否具備原子性,所以這裡暫時只是分享一些觀點,我個人稍微傾向於相信它不是原子性的,但是也希望大佬多指教:
- 因為IBM文章的實驗和我自己的實驗都表明並不是「一起結束的」。因為部分數據已經發送了,另一部分最後才發送。
- 認為是原子性的觀點沒有給出實質的論據。
4.1.1 認為POSIX標準下不是原子性的觀點和依據
以下摘自IBM文章
the POSIX/SUSv3 standard developers indicate that atomicity for socket I/O is “unspecified”.
Why not atomic?
Using Linux kernel 2.6.11 as a reference, because it’s the latest kernel processed for easy web cross-referencing at LXR
When a connected TCP send(), sendto(), or sendmsg() arrives in the Linux kernel, it eventually comes through tcp_sendmsg(). tcp_sendmsg() protects itself by acquiring a lock at invocation by calling lock_sock(). tcp_sendmsg() then loops over the buffers in the iovec, allocating associated sk_buff’s and cache pages for use in the actual send. As it does so, it pushes the data out to tcp for actual transmission. However, if one of those allocation fails (because a large number of large sends is being processed, for example), it must wait for memory to become available. It does so by jumping to wait_for_sndbuf or wait_for_memory, both of which eventually cause a call to sk_stream_wait_memory(). sk_stream_wait_memory() contains a code path that calls sk_wait_event(). Finally, sk_wait_event() contains the call to release_sock().
At this point, any one of the threads that were heretofore serialized at the initial call to lock_sock() in tcp_sendmsg() can proceed. Memory may either become available, or a small enough send may not require enough memory to block and may proceed immediately, thus intermixing data from one call to send() with another.
but in the definition of read() in the IEEE Std 1003.1-2001 System Interfaces volume, it gives the following rationale: “The standard developers considered adding atomicity requirements…”
4.1.1 認為POSIX標準下是原子性的觀點和依據
以下認為send是系統調用, 是原子操作, 不會在內核中有競爭. 但是這個和IBM文章就有矛盾了.IBM文章的分析應該是有競爭的(當多個線程同時send). 雖然他認為是原子的, 但也認為多個線程同時發送也要保證同步問題, 以免內容交錯.
A lock is not required; send() is a syscall, it is an atomic operation with no race conditions in the kernel.For stream sockets (TCP) too, the send() function is atomic; but there is no concept of distinct messages or packets, the data treated as a single stream of bytes. So even though send() is thread-safe, synchronisation is required to ensure that the bytes from different send calls are merged into the byte stream in a predictable manner.
以下的觀點也認為是原子的, 但是他說send的調用總是完全成功, 或者完全失敗, 但是實際上send是可以返回小於請求值的(也就是小於待發送的數據長度).
Sorry, you’re wrong. Send is 100% an atomic operation. If the data is too large and won’t fit in the output buffer, then the call will block. If the call to send is interrupted, then no data is sent and an error is returned. Calls to send always completely succeed, or completely fail.
摘自: //stackoverflow.com/questions/3235424/c-sockets-send-thread-safety
4.2 Linux man pages的觀點真的錯了嗎
以下摘自:Linux man pages //man7.org/linux/man-pages/man2/send.2.html
If space is not available at the sending socket to hold the message to be transmitted, and the socket file descriptor does not have O_NONBLOCK set, send() shall block until space is available.
When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in nonblocking I/O mode. In nonblocking mode it would fail with the error EAGAIN or EWOULDBLOCK in this case. The select(2) call may be used to determine when it is possible to send more data.
意思是如果socket緩衝區不能裝下待發送的數據,則send函數會阻塞直到內存可用,然後發送。
上一節ibm文章依據實驗結果,認為並沒有阻塞,從而判斷man pages的這一觀點是錯的。
我的觀點上節也說了:但是這只是一種可能,我們只能判斷一定是釋放了鎖,且被別的線程競爭到了鎖,是不是只有內存分配失敗才會導致這樣呢?我也不太確定
4.3 UDP會不會遇到和tcp一樣的問題
據所有收集的資料的說法:不會。
因為udp是數據報大小受限(UDP不具備分片能力,或者說不具備分片後,對端正確組包的能力),因此不像tcp發送這麼大的數據,他們的操作會很快發送(不會像前面分析的,還會等待內存分配而阻塞),因此「看上去」udp的操作是原子的。
以下是支持這個觀點的資料:
Note that datagram sockets (UDP) are connection-less, so the the datagram packets may be delivered in a sequence that is different from the sequence in which they were sent (even if all the send calls were from within a single thread).
Q: can I concurrently have two threads at the same time write (sendto) on a same file descriptor? How about readfrom and sendt on the same file descriptor at the same time?
A: Yes, but assume two threads A (writes a one message containing “aaaa”)
and B which (writes two messages “b” and “c”).You can be assured that B’s data won’t show up inside A’s message:
ie. never aabaa
but you can not assume anything about the order they will be received.摘自: //linux-newbie.vger.kernel.narkive.com/wdAJ3Kzt/is-sendto-and-recvfrom-thread-safe#post4
對於 UDP,多線程讀寫同一個 socket 不用加鎖,不過更好的做法是每個線程有自己的 socket,避免 contention,可以用 SO_REUSEPORT 來實現這一點。
對於 TCP,通常多線程讀寫同一個 socket 是錯誤的設計,因為有 short write 的可能。假如你加鎖,而又發生 short write,你是不是要一直等到整條消息發送完才解鎖(無論阻塞IO還是非阻塞IO)?如果這樣,你的臨界區長度由對方什麼時候接收數據來決定,一個慢的 peer 就把你的程序搞死了。
總結:對於 UDP,加鎖是多餘的;對於 TCP,加鎖是錯誤的。
摘自知乎陳碩大佬的回答: //www.zhihu.com/question/56899596/answer/150926723
4.4 fwrite是不是線程安全的
fwrite是c/c++語言庫實現的,它最終是調用write系統調用,但是做了一些封裝,關於FILE*等可以看我之前的內容://www.cnblogs.com/whuwzp/p/stdin_stdout_fflush_file.html。
另外這篇文章用實驗證明了fwrite的線程安全性://cloud.tencent.com/developer/article/1412015 (但是我和他關於write的線程安全性的實驗的結果是不一樣的,我測試是也具備線程安全性的,即使不加APPEND模式)
在同一個進程內, 針對同一個FILE*的操作(比如fwrite), 是線程安全的. 當然這隻在POSIX兼容的系統上成立, Windows上的FILE*的操作並不是線程安全的.
//gcc.gnu.org/onlinedocs/libstdc++/manual/using_concurrency.htmlAs a n example, the POSIX standard requires that C stdio FILE* operations are atomic. POSIX-conforming C libraries (e.g, on Solaris and GNU/Linux) have an internal mutex to serialize operations on FILE*s. However, you still need to not do stupid things like calling fclose(fs) in one thread followed by an access of fs in another.
摘自知乎大神egmkang wang的回答: //www.zhihu.com/question/40472431/answer/87077691
It depends upon which primitives you’re using to submit data to the socket.
If you’re using write(2), send(2), sendto(2), or sendmsg(2) and the size of your message is small enough to fit entirely within the kernel buffers for the socket, then that entire write will be sent as a block without other data being interspersed.
摘自://stackoverflow.com/questions/7942595/linux-c-c-socket-send-in-multi-thread-code
4.5 Windows 平台,java語言,c++ boost庫 相關討論
- Winsock環境下UDP不存在線程安全問題而tcp存在的資料://stackoverflow.com/questions/13983398/is-winsock2-thread-safe
- Windows 下使用多個線程send,結論是無法保證順序,以及內容會不會交錯://tangentsoft.net/wskfaq/intermediate.html#threadsafety
- 一個boost的測試,結論是boost的不是線程安全的(多個線程同時send):
//stackoverflow.com/questions/11581978/write-to-boostasio-socket-from-different-threads - java裏面的,高概率數據交錯,除非兩個線程自有順序(不同時),或者寫入是原子操作,不然很可能交錯://stackoverflow.com/questions/18910022/can-two-threads-use-the-same-socket-at-the-same-time-and-are-there-possible-pro
5. 建議和替代方案
無論什麼平台,都不要嘗試多線程send。
- Linux下:改成消息隊列模型,多個線程把數據發送到隊列中(隊列用mutex等保證線程安全),然後僅由一個線程負責取出消息隊列中的消息,發送給對端。可以參考libevent和這篇文章//pl.atyp.us/content/tech/servers.html。
- Windows下:asynchronous IO or overlapped IO (這個不太熟)
6. 參考網址
- IBM文章:原文已失效,轉載的://www.cnblogs.com/whuwzp/articles/thread_safe
- UDP不存在線程安全問題的資料://linux-newbie.vger.kernel.narkive.com/wdAJ3Kzt/is-sendto-and-recvfrom-thread-safe#post4
- Winsock環境下UDP不存在線程安全問題而tcp存在的資料://stackoverflow.com/questions/13983398/is-winsock2-thread-safe
- Windows 下使用多個線程send,結論是無法保證順序,以及內容會不會交錯://tangentsoft.net/wskfaq/intermediate.html#threadsafety
- 一個boost的測試,結論是boost的不是線程安全的(多個線程同時send):
//stackoverflow.com/questions/11581978/write-to-boostasio-socket-from-different-threads - java裏面的,高概率數據交錯,除非兩個線程自有順序(不同時),或者寫入是原子操作,不然很可能交錯://stackoverflow.com/questions/18910022/can-two-threads-use-the-same-socket-at-the-same-time-and-are-there-possible-pro
- 和我相同問題的://stackoverflow.com/questions/1457256/is-it-safe-to-issue-blocking-write-calls-on-the-same-tcp-socket-from-multiple
- 原子和線程安全的討論: //softwareengineering.stackexchange.com/questions/178898/difference-between-atomic-operation-and-thread-safety
- 原子和線程安全的討論: //stackoverflow.com/questions/12347236/which-is-threadsafe-atomic-or-non-atomic
- 知乎陳碩大佬的關於該問題加鎖解決的方法的評價: //www.zhihu.com/question/56899596/answer/150926723
- 知乎大神egmkang wang的回答fwrite線程安全性: //www.zhihu.com/question/40472431/answer/87077691