Skip to content

Commit 87edccf

Browse files
committed
Reduce synchronization overhead of I/O vector count memoization
1 parent 6672f7b commit 87edccf

File tree

1 file changed

+14
-10
lines changed
  • library/std/src/sys/unix

1 file changed

+14
-10
lines changed

library/std/src/sys/unix/fd.rs

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
use crate::cmp;
44
use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read};
5-
use crate::lazy::SyncOnceCell;
65
use crate::mem;
6+
use crate::sync::atomic::{AtomicUsize, Ordering};
77
use crate::sys::cvt;
88
use crate::sys_common::AsInner;
99

@@ -28,10 +28,11 @@ const READ_LIMIT: usize = c_int::MAX as usize - 1;
2828
const READ_LIMIT: usize = libc::ssize_t::MAX as usize;
2929

3030
#[cfg(any(target_os = "linux", target_os = "macos"))]
31-
fn max_iov() -> c_int {
32-
static LIM: SyncOnceCell<c_int> = SyncOnceCell::new();
31+
fn max_iov() -> usize {
32+
static LIM: AtomicUsize = AtomicUsize::new(0);
3333

34-
*LIM.get_or_init(|| {
34+
let mut lim = LIM.load(Ordering::Relaxed);
35+
if lim == 0 {
3536
let ret = unsafe {
3637
libc::sysconf(
3738
#[cfg(target_os = "linux")]
@@ -43,13 +44,16 @@ fn max_iov() -> c_int {
4344

4445
// 1024 is the default value on modern Linux systems
4546
// and hopefully more useful than `c_int::MAX`.
46-
if ret > 0 { ret as c_int } else { 1024 }
47-
})
47+
lim = if ret > 0 { ret as usize } else { 1024 };
48+
LIM.store(lim, Ordering::Relaxed);
49+
}
50+
51+
lim
4852
}
4953

5054
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
51-
fn max_iov() -> c_int {
52-
c_int::MAX
55+
fn max_iov() -> usize {
56+
c_int::MAX as usize
5357
}
5458

5559
impl FileDesc {
@@ -80,7 +84,7 @@ impl FileDesc {
8084
libc::readv(
8185
self.fd,
8286
bufs.as_ptr() as *const libc::iovec,
83-
cmp::min(bufs.len(), max_iov() as usize) as c_int,
87+
cmp::min(bufs.len(), max_iov()) as c_int,
8488
)
8589
})?;
8690
Ok(ret as usize)
@@ -137,7 +141,7 @@ impl FileDesc {
137141
libc::writev(
138142
self.fd,
139143
bufs.as_ptr() as *const libc::iovec,
140-
cmp::min(bufs.len(), max_iov() as usize) as c_int,
144+
cmp::min(bufs.len(), max_iov()) as c_int,
141145
)
142146
})?;
143147
Ok(ret as usize)

0 commit comments

Comments
 (0)