From 8c2eabed5ac02a93e1cf0aa4d811167d34845375 Mon Sep 17 00:00:00 2001
From: Nicolas Pope <nicolas.pope@utu.fi>
Date: Wed, 8 Jun 2022 10:06:28 +0000
Subject: [PATCH] #22 Change winsock startup

---
 src/socket/socket_windows.cpp | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/src/socket/socket_windows.cpp b/src/socket/socket_windows.cpp
index c4c8559..8334b5c 100644
--- a/src/socket/socket_windows.cpp
+++ b/src/socket/socket_windows.cpp
@@ -39,19 +39,25 @@ bool ftl::net::internal::resolve_inet_address(const std::string& hostname, int p
     return true;
 }
 
-static std::atomic_bool is_initialized_;
-static WSAData wsaData_;
-
-Socket::Socket(int domain, int type, int protocol) :
-    status_(STATUS::UNCONNECTED), fd_(-1), family_(domain) {
-    if (!is_initialized_.exchange(true)) {
+class WinSock {
+ public:
+    WinSock() {
         if (WSAStartup(MAKEWORD(1, 1), &wsaData_) != 0) {
             LOG(FATAL) << "could not initialize sockets";
             // is it possible to retry/recover?
         }
     }
 
-    // TODO(Seb): initialization might not be complete if called from another thread
+ private:
+    WSAData wsaData_;
+};
+
+// Do WSAStartup as static initialisation so no threads active.
+static WinSock winSock;
+
+Socket::Socket(int domain, int type, int protocol) :
+    status_(STATUS::UNCONNECTED), fd_(-1), family_(domain) {
+
     fd_ = ::socket(domain, type, protocol);
     if (fd_ == INVALID_SOCKET) {
         err_ = WSAGetLastError();
-- 
GitLab