Microsoft MVP성태의 닷넷 이야기
VC++: 70. Win32 socket이 Thread-safe할까? [링크 복사], [링크+제목 복사],
조회: 20828
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Win32 socket이 Thread-safe할까?

지난번에는 닷넷의 System.Net.Sockets.Socket 타입에 대한 thread-safe 이야기를 했었는데요.

System.Net.Sockets.Socket이 Thread-safe할까?
; https://www.sysnet.pe.kr/2/0/1469

그럼, 이번에는 닷넷의 하위로 내려가서 윈도우 운영체제의 socket에 대한 thread-safe 문제를 살펴보겠습니다. 검색을 좀 해보면 이에 대해서 많은 질문/답변이 있는 것을 확인할 수 있는데, 그만큼 의견도 다양합니다. ^^ 우선, thread-safe하지 않다는 몇몇 글을 볼까요?

Is Winsock thread-safe?
; http://tangentsoft.net/wskfaq/intermediate.html#threadsafety

C socket API is thread safe?
; http://stackoverflow.com/questions/2354417/c-socket-api-is-thread-safe

첫 번째 글에서는 send/receive에 대한 동시 호출은 안전하지만 send/send는 그렇지 않다고 합니다. 두 번째 글의 덧글에는 "Sending data via a socket is not a atomic transaction - any non-atomic transaction will require a lock/synchronisation. This is independent of the platform."라고 해서 역시 thread-safe하지 않다고 합니다.

반면에 다음의 글에서는 의견이 다릅니다.

Are parallel calls to send/recv on the same socket valid?
; http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid

위의 덧글에는 다음과 같은 설명을 포함합니다.

1) POSIX defines send/recv as atomic operations

2) The socket descriptor belongs to the process, not to a particular thread. Hence, it is possible to send/receive to/from the same socket in different threads, the OS will handle the synchronization.


애석하게도 이건 그들의 의견일 뿐 명백하게 문서화된 내용이 없다는 것이 문제입니다. 저도 MSDN 문서에서 socket 관련한 내용을 뒤져보았지만 마이크로소프트는 이에 대해 thread safe/not-safe에 대한 어떠한 명시도 하지 않고 있습니다.

따라서, 이 글의 결론은 마이크로소프트에 의해 공식적으로 확인된 것은 아니고 제 개인적인 의견을 담고 있다는 것을 미리 ^^ 밝혀두는 바입니다.




이거저거 조사해 보면 일단 제 의견은 Win32에서 제공되는 socket.send가 thread-safe 하다는 쪽에 무게를 두고 있습니다. 왜냐고요? ^^

우선, 지난번 글에 쓴 것처럼 Microsoft는 Win32 Socket에 대한 thread-safe는 명시하지 않았지만 .NET Framework의 Socket에 대한 thread-safe은 명시를 했습니다. 이게 어떤 의미를 갖냐면... .NET도 결국 내부적으로는 Win32 Socket의 send를 호출하기 때문에 간접적인 증거로 작용할 수 있습니다. 실제로 System.Net.Sockets.Socket.Send 메소드를 .NET Reflector로 보면 다음과 같이 어떠한 내부적인 잠금 없이 곧바로 Win32 send를 호출하는 것을 확인할 수 있습니다.

public unsafe int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
{
    // ...[생략]...

    if (buffer.Length == 0)
    {
        num = UnsafeNclNativeMethods.OSSOCK.send(this.m_Handle.DangerousGetHandle(), null, 0, socketFlags);
    }
    else
    {
        fixed (byte* numRef = buffer)
        {
            num = UnsafeNclNativeMethods.OSSOCK.send(this.m_Handle.DangerousGetHandle(), numRef + offset, size, socketFlags);
        }
    }

    // ...[생략]...
    return num;
}

[DllImport("ws2_32.dll", SetLastError=true)]
internal static extern unsafe int send([In] IntPtr socketHandle, [In] byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags);

따라서, Win32 Socket 역시 thread-safe 하다는 결론이 나옵니다.

또 다른 간접적인 증거가 하나 있다면 WSASend에 설명된 MSDN의 문서입니다.

WSASend function
; https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasend

If you are using I/O completion ports, be aware that the order of calls made to WSASend is also the order in which the buffers are populated. WSASend should not be called on the same socket simultaneously from different threads, because it can result in an unpredictable buffer order.

위의 글에서는 WSASend가 "I/O completion ports"를 사용하는 상황에서는 버퍼 관리 때문에 thread-safe하지 않다고 나옵니다. 만약, 소켓 자체가 thread-safe하지 않았으면 애당초 이런 글이 나왔을리 없으므로, 조심스럽게 소켓이 thread-safe하지 않을까 하는 결론이 나옵니다.




비록 문서상으로 명확하게 밝혀진 것은 아니지만, 이에 대해 지난번 글에서 했던 것과 동일한 테스트를 통해 검증해 보는 것은 어떨까요? ^^

우선, C/C++ 클라이언트 프로그램을 단일 스레드 예제로 닷넷 소켓 서버와 호환되게 맞춰서 만들어 보았습니다.

#include "stdafx.h"

#include <Windows.h>
#include <WinSock2.h>

#include "CommonPacket.h"

#pragma comment(lib, "Ws2_32.lib")

#include <string>

using namespace std;

bool MustSendBuffer(SOCKET socket, byte *dataBuf, int mustSend);

int _tmain(int argc, _TCHAR* argv[])
{
    ::Sleep(2000);

    string body = "";
    string chunk = "";

    for (int i = 0; i < 10; i ++)
    {
        chunk += to_string(i);  
    }

    int loopCount = 10000;

    for (int i = 0; i < loopCount; i ++)
    {
        body += chunk;
    }

	/*
	UTF-8 CPP
	; http://sourceforge.net/projects/utfcpp/
	*/

    // 문자열을 utf-8 인코딩 시키고
    vector<unsigned char> dataBuf;
    utf8::utf16to8(body.begin(), body.end(), back_inserter(dataBuf));

    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != NO_ERROR) 
    {
        wprintf(L"WSAStartup function failed with error: %d\n", result);
        return 1;
    }

    SOCKET socket = INVALID_SOCKET;

    do
    {
        sockaddr_in target;
        target.sin_family = AF_INET;
        // target.sin_addr.s_addr = inet_addr("192.168.0.70");

        target.sin_addr.s_addr = inet_addr("127.0.0.1");
        target.sin_port = htons(11200);

        socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (socket == INVALID_SOCKET)
        {
            wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
            break;
        }

        result = ::connect(socket, (SOCKADDR *)&target, sizeof(target));
        if (result == SOCKET_ERROR) 
        {
            wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
            break;
        }

        int instanceId = 0;
        ::send(socket, (const char *)&instanceId, sizeof(int), 0);

        for (int i = 0; i < loopCount; i++)
        {
            CommonPacket packet(i);
            packet.AddData(dataBuf);

            BYTE *dataBuf = packet.GetBuffer();
            int bufferSize = packet.GetBufferSize();

            MustSendBuffer(socket, dataBuf, bufferSize);
        }

    } while (false);

    if (socket != INVALID_SOCKET)
    {
        result = ::closesocket(socket);
        if (result == SOCKET_ERROR)
        {
            wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
        }

        socket = INVALID_SOCKET;
        printf("TCP Client socket: Closed\n");
    }

    WSACleanup();

    return 0;
}

bool MustSendBuffer(SOCKET socket, byte *dataBuf, int mustSend)
{
    int pos = 0;

    while (true)
    {
        int sentLength = ::send(socket, (const char *)dataBuf + pos, mustSend, 0);
        if (sentLength == 0)
        {
            return false;
        }

        if (sentLength == -1)
        {
            printf("Socket Failed: %d", ::WSAGetLastError());
            return false;
        }

        mustSend -= sentLength;
        pos += sentLength;
        if (mustSend == 0)
        {
            return true;
        }
    }
}

물론 단일 스레드 예제이므로 잘 동작합니다. ^^ 그다음, 이것을 다중 스레드로 버전으로 바꿔 보았습니다.

#include "stdafx.h"

#include <Windows.h>
#include <WinSock2.h>

#include "..\SocketClientST\CommonPacket.h"

#pragma comment(lib, "Ws2_32.lib")

#include <string>
#include <thread>
#include <ppl.h>

using namespace std;

typedef struct tagThreadParam
{
    int Sent;

    Concurrency::critical_section *Sync;
    SOCKET ClientSocket;
    vector<CommonPacket *> *Packets;

} ThreadParam;

bool MustSendBuffer(SOCKET socket, byte *dataBuf, int mustSend);

void sendBufferThread(ThreadParam *threadParam)
{
    while (true)
    {
        CommonPacket *packet = nullptr;

        threadParam->Sync->lock();
        {
            if (threadParam->Packets->size() != 0)
            {
                packet = threadParam->Packets->back();
                threadParam->Packets->pop_back();

                threadParam->Sent ++;
            }
        }
        threadParam->Sync->unlock();

        if (packet == nullptr)
        {
            break;
        }

        BYTE *dataBuf = packet->GetBuffer();
        int bufferSize = packet->GetBufferSize();

        MustSendBuffer(threadParam->ClientSocket, dataBuf, bufferSize);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    ::Sleep(2000);

    string body = "";
    string chunk = "";

    for (int i = 0; i < 10; i ++)
    {
        chunk += to_string(i);  
    }

    int loopCount = 10000;

    for (int i = 0; i < loopCount; i ++)
    {
        body += chunk;
    }

    vector<unsigned char> dataBuf;
    utf8::utf16to8(body.begin(), body.end(), back_inserter(dataBuf));

    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != NO_ERROR) 
    {
        wprintf(L"WSAStartup function failed with error: %d\n", result);
        return 1;
    }

    SOCKET socket = INVALID_SOCKET;

    do
    {
        sockaddr_in target;
        target.sin_family = AF_INET;
        // target.sin_addr.s_addr = inet_addr("192.168.0.70");

        target.sin_addr.s_addr = inet_addr("127.0.0.1");
        target.sin_port = htons(11200);

        socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (socket == INVALID_SOCKET)
        {
            wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
            break;
        }

        result = ::connect(socket, (SOCKADDR *)&target, sizeof(target));
        if (result == SOCKET_ERROR) 
        {
            wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
            break;
        }

        int instanceId = 0;
        ::send(socket, (const char *)&instanceId, sizeof(int), 0);

        vector<CommonPacket *> packets;

        for (int i = 0; i < loopCount; i ++)
        {
            CommonPacket *packet = new CommonPacket(i);
            packet->AddData(dataBuf);

            packets.push_back(packet);
        }

        vector<std::thread *> threads;

        ThreadParam param;
        Concurrency::critical_section sync;

        param.Sync = &sync;
        param.Packets = &packets;
        param.ClientSocket = socket;

        // 20개의 스레드를 만들어서,
        // vector에 담아둔 CommonPacket 내용을 socket send API를 통해 서버로 전송
        for (int i = 0; i < 20; i ++)
        {
            thread *aThread = new thread(sendBufferThread, &param);
            threads.push_back(aThread);
        }

        for (size_t i = 0; i < threads.size(); i ++)
        {
            threads[i]->join();
            delete threads[i];
        }

        threads.clear();

        for (size_t i = 0; i < packets.size(); i ++)
        {
            delete packets[i];
        }

        packets.clear();

    } while (false);

    if (socket != INVALID_SOCKET)
    {
        result = ::closesocket(socket);
        if (result == SOCKET_ERROR)
        {
            wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
        }

        socket = INVALID_SOCKET;
        printf("TCP Client socket: Closed\n");
    }

    WSACleanup();

    return 0;
}

오~~~ 훌륭합니다. ^^ C/C++ 표준의 발전으로 threads가 포함되어 지난번에 작성했던 C# 예제를 거의 1:1 매핑 식으로 C/C++로 포팅하는 작업이 자연스럽게 이뤄집니다.

결과를 실행해 보면 닷넷의 Socket 때와 마찬가지로 서버 측에서의 데이터 검증 작업이 성공하는 것을 확인할 수 있습니다. (물론, 지난번 글에도 언급했지만, 이건 실험값에 불과하다는 점을 간과해서는 안됩니다.)

이 글에서 사용된 C/C++ 예제 역시 첨부해 두었습니다. (참고로, 서버 예제는 지난번 글의 코드와 완전히 동일합니다.) 이번에도 역시 테스트 코드의 조건에 의문 사항이나 개선이 필요하면 덧글 부탁드립니다




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/25/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2014-06-19 02시53분
Modern C++ 프로그래머를 위한 CPP11/14 핵심
; http://www.slideshare.net/jacking/modern-c-cpp11-14
정성태

1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13323정성태4/16/20234559개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235397VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20234189개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20234066개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234588개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234461개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234503오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233763오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20234080Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20234205개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20234215개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20234279Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234706C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234364C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234475.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234429스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20234173.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20234068Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234400Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234693VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20234038Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234636Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234790Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234510Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20234247Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20234224Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...