Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does AtomicUsize not implement Send?

Tags:

std::sync::atomic::AtomicUsize implements Sync which means immutable references are free of data races when shared between multiple threads. Why does AtomicUsize not implement Send? Is there state which is linked to the thread that created the atomic or is this a language design decision relating to the way atomics are intended to be used i.e. via a Arc<_> etc.

like image 528
J. Dunne Avatar asked May 05 '16 23:05

J. Dunne


1 Answers

It's a trick! AtomicUsize does implement Send:

use std::sync::atomic::AtomicUsize;

fn checker<T>(_: T) where T: Send {}

fn main() {
    checker(AtomicUsize::default());
}

In fact, there's even an automated test that ensures this is the case.

Rust 1.26

These auto traits are now documented, thanks to a change made to rustdoc.

Previous versions

The gotcha lies in how Send is implemented:

This trait is automatically derived when the compiler determines it's appropriate.

This means that Rustdoc doesn't know that Send is implemented for a type because most types don't implement it explicitly.

This explains why AtomicPtr<T> shows up in the implementers list: it has a special implementation that ignores the type of T.

like image 93
Shepmaster Avatar answered Oct 12 '22 11:10

Shepmaster