diff --git a/library/std/src/sys/net/connection/socket/windows.rs b/library/std/src/sys/net/connection/socket/windows.rs index ce975bb2289c2..5f3e16213a1c9 100644 --- a/library/std/src/sys/net/connection/socket/windows.rs +++ b/library/std/src/sys/net/connection/socket/windows.rs @@ -8,7 +8,8 @@ use crate::net::{Shutdown, SocketAddr}; use crate::os::windows::io::{ AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket, }; -use crate::sync::OnceLock; +use crate::sync::atomic::Atomic; +use crate::sync::atomic::Ordering::{AcqRel, Relaxed}; use crate::sys::c; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; @@ -114,35 +115,36 @@ pub(super) mod netc { #[expect(missing_debug_implementations)] pub struct Socket(OwnedSocket); -static WSA_CLEANUP: OnceLock i32> = OnceLock::new(); +static WSA_INITIALIZED: Atomic = Atomic::::new(false); /// Checks whether the Windows socket interface has been started already, and /// if not, starts it. +#[inline] pub fn init() { - let _ = WSA_CLEANUP.get_or_init(|| unsafe { + if !WSA_INITIALIZED.load(Relaxed) { + wsa_startup(); + } +} + +#[cold] +fn wsa_startup() { + unsafe { let mut data: c::WSADATA = mem::zeroed(); let ret = c::WSAStartup( 0x202, // version 2.2 &mut data, ); assert_eq!(ret, 0); - - // Only register `WSACleanup` if `WSAStartup` is actually ever called. - // Workaround to prevent linking to `WS2_32.dll` when no network functionality is used. - // See issue #85441. - c::WSACleanup - }); -} - -pub fn cleanup() { - // only perform cleanup if network functionality was actually initialized - if let Some(cleanup) = WSA_CLEANUP.get() { - unsafe { - cleanup(); + if WSA_INITIALIZED.swap(true, AcqRel) { + // If another thread raced with us and called WSAStartup first then call + // WSACleanup so it's as though WSAStartup was only called once. + c::WSACleanup(); } } } +pub fn cleanup() {} + /// Returns the last error from the Windows socket interface. fn last_error() -> io::Error { io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })