Commit graph

304 commits

Author SHA1 Message Date
Marius Nuennerich
73b656bbb3
Fix small typo in comment 2018-11-27 18:57:55 +01:00
Andy Russell
4e35cbb22e
fix various typos in doc comments 2018-11-13 14:45:31 -05:00
kennytm
462f63e1bb
Rollup merge of #55597 - alexcrichton:thread-local-inner, r=KodrAus
std: Enable usage of `thread_local!` through imports

The `thread_local!` macro delegated to an internal macro but it didn't
do so in a macros-and-the-module-system compatible fashion, meaning if a
`#![no_std]` crate imported `std` and tried to use `thread_local!` it
would fail due to missing a lookup of an internal macro.

This commit switches the macro to instead use `$crate` to invoke other
macros, ensuring that it'll work when `thread_local!` is imported alone.
2018-11-06 17:08:03 +08:00
Alex Crichton
ff5226cd2f std: Enable usage of thread_local! through imports
The `thread_local!` macro delegated to an internal macro but it didn't
do so in a macros-and-the-module-system compatible fashion, meaning if a
`#![no_std]` crate imported `std` and tried to use `thread_local!` it
would fail due to missing a lookup of an internal macro.

This commit switches the macro to instead use `$crate` to invoke other
macros, ensuring that it'll work when `thread_local!` is imported alone.
2018-11-01 14:17:39 -07:00
Alex Crichton
0c3d08e967 std: Improve codegen size of accessing TLS
Some code in the TLS implementation in libstd stores `Some(val)` into an
`&mut Option<T>` (effectively) and then pulls out `&T`, but it currently
uses `.unwrap()` which can codegen into a panic even though it can never
panic. With sufficient optimizations enabled (like LTO) the compiler can
see through this but this commit helps it along in normal mode
(`--release` with Cargo by default) to avoid codegen'ing the panic path.

This ends up improving the optimized codegen on wasm by ensuring that a
call to panic pulling in more file size doesn't stick around.
2018-11-01 10:46:31 -07:00
James Duley
d3e71e4986 thread::unpark: Avoid notifying with mutex locked.
This means when the other thread wakes it can continue right away
instead of having to wait for the mutex.

Also add some comments explaining why the mutex needs to be locked in
the first place.
2018-10-30 22:54:35 +00:00
bors
bcb05a0ab2 Auto merge of #55043 - oliver-giersch:unchecked_thread_spawning, r=alexcrichton
Unchecked thread spawning

# Summary

Add an unsafe interface for spawning lifetime-unrestricted threads for
library authors to build less-contrived, less-hacky safe abstractions
on.

# Motivation

So a few years back scoped threads were entirely removed from the Rust
stdlib, the reason being that it was possible to leak the scoped thread's
join guards without resorting to unsafe code, which meant the concept
was not completely safe, either.
Only a maximally-restrictive safe API for thread spawning was kept in the
stdlib, that requires `'static` lifetime bounds on both the thread closure
and its return type.
A number of 3rd party libraries sprung up to offer their implementations
for safe scoped threads implementations.
These work by essentially hiding the join guards from the user, thus
forcing them to join at the end of an (internal) function scope.

However, since these libraries have to use the maximally restrictive
thread spawning API, they have to resort to some very contrived manipulations
and subversions of Rust's type system to basically achieve what this commit does
with some minimal restructuring of the current code and exposing a new unsafe
function signature for spawning threads without lifetime restrictions.
Obviously this is unsafe, but its main use would be to allow library authors
to write safe abstractions with and around it.
To further illustrate my point, here's a quick summary of the hoops that,
for instance `crossbeam`, has to jump through to spawn a lifetime unrestricted
thread, all of which would not be necessary if an unsafe API existed as part
of the stdlib:

1. Allocate an `Arc<Option<T>>` on the heap where the result with type
`T: 'a` will go (in practice requires `Mutex` or `UnsafeCell` as well).

2. Wrap the desired thread closure with lifetime bound `'a` into another
closure (also `..: 'a`) that returns `()`, executes the inner closure and
writes its result into the pre-allocated `Option<T>`.

3. Box the wrapping closure, cast it to a trait object (`FnBox`) and
(unsafely) transmute its lifetime bound from `'a` to `'static`.

So while this new `spawn_unchecked` function is certainly not very relevant
for general use, since scoped threads are so common I think it makes sense
to expose an interface for libraries implementing these to build on.
The changes implemented are also very minimal: The current `spawn` function
(which internally contains unsafe code) is moved into an unsafe `spawn_unchecked`
function, which the safe function then wraps around.

# Issues

- ~~so far, no documentation for the new function (yet)~~
- the name of the function might be controversial, as `*_unchecked` more commonly
indicates that some sort of runtime check is omitted (`unrestricted` may be
more fitting)
- if accepted, it might make sense to add a freestanding `thread::spawn_unchecked`
function similar to the current `thread::spawn` for convenience.
2018-10-28 21:34:12 +00:00
kennytm
e4ac447851
Rollup merge of #54646 - vn971:fix_std_thread_sleep, r=frewsxcv
improve documentation on std:🧵:sleep
2018-10-18 12:54:42 +08:00
oliver-giersch
7849aeddb9
adds tracking issue number 2018-10-16 22:42:14 +02:00
oliver-giersch
30bfdc8720
Merge pull request #5 from oliver-giersch/master
sync with upstream
2018-10-15 14:38:34 +02:00
oliver-giersch
ebb9d289db
adds feature gate to doc-test (example) 2018-10-15 14:14:17 +02:00
oliver-giersch
ee5703cbbc
adds missing method call parentheses 2018-10-15 13:47:27 +02:00
oliver-giersch
9d7a83862b
fixes misplaced semicolon 2018-10-15 13:22:39 +02:00
oliver-giersch
986549e9f5
adds doc for Builder::spawn_unchecked 2018-10-15 12:48:24 +02:00
oliver-giersch
bf9dc98655
remove unnecessary lifetime bounds
generic lifetime bound `'a` can be inferred.
2018-10-14 14:28:01 +02:00
oliver-giersch
a52b474b52
Update mod.rs
removes trailing whitespaces, replaces TODO with FIXME
2018-10-13 18:24:47 +02:00
oliver-giersch
719a59586a
Update mod.rs
removes unnecessary `unsafe`, adds `unstable` attribute
2018-10-13 17:28:47 +02:00
oliver-giersch
fbb95689d6
adds unsafe thread::Builder::spawn_unchecked function
moves code for `thread::Builder::spawn` into new public unsafe function `spawn_unchecked` and transforms `spawn` into a safe wrapper.
2018-10-13 14:34:31 +02:00
Vasya Novikov
7a0fa95336
improve docs on thread::sleep 2018-10-11 21:37:30 +03:00
Alex Crichton
cbe9f33b8b std: Implement TLS for wasm32-unknown-unknown
This adds an implementation of thread local storage for the
`wasm32-unknown-unknown` target when the `atomics` feature is
implemented. This, however, comes with a notable caveat of that it
requires a new feature of the standard library, `wasm-bindgen-threads`,
to be enabled.

Thread local storage for wasm (when `atomics` are enabled and there's
actually more than one thread) is powered by the assumption that an
external entity can fill in some information for us. It's not currently
clear who will fill in this information nor whose responsibility it
should be long-term. In the meantime there's a strategy being gamed out
in the `wasm-bindgen` project specifically, and the hope is that we can
continue to test and iterate on the standard library without committing
to a particular strategy yet.

As to the details of `wasm-bindgen`'s strategy, LLVM doesn't currently
have the ability to emit custom `global` values (thread locals in a
`WebAssembly.Module`) so we leverage the `wasm-bindgen` CLI tool to do
it for us. To that end we have a few intrinsics, assuming two global values:

* `__wbindgen_current_id` - gets the current thread id as a 32-bit
  integer. It's `wasm-bindgen`'s responsibility to initialize this
  per-thread and then inform libstd of the id. Currently `wasm-bindgen`
  performs this initialization as part of the `start` function.
* `__wbindgen_tcb_{get,set}` - in addition to a thread id it's assumed
  that there's a global available for simply storing a pointer's worth
  of information (a thread control block, which currently only contains
  thread local storage). This would ideally be a native `global`
  injected by LLVM, but we don't have a great way to support that right
  now.

To reiterate, this is all intended to be unstable and purely intended
for testing out Rust on the web with threads. The story is very likely
to change in the future and we want to make sure that we're able to do
that!
2018-10-11 09:57:55 -07:00
Artem Varaksa
ddcec08a54 Fix typo in libstd/thread/mod.rs: remove unnecessary comma 2018-10-06 20:09:54 +03:00
Vasya Novikov
b63517a2c3 update wording for thread::sleep 2018-10-01 11:01:15 +03:00
Vasya Novikov
049ccbb174 update wording for std:🧵:sleep 2018-09-28 22:40:20 +03:00
Vasya Novikov
1a605a6bda fix std:🧵:sleep typo 2018-09-28 19:36:53 +03:00
James Duley
a3b87058e7 Expand synchronization comments in park/unpark 2018-09-18 18:06:16 +01:00
James Duley
f8a78bdfdf Add comments and assertion to park/unpark
regarding the synchronization.
2018-09-14 17:35:12 +01:00
James Duley
204d9608e3 Fix thread park/unpark synchronization
Previously the code below would not be guaranteed to exit when the first
spawned thread took the `return, // already unparked` path because there
was no write to synchronize with a read in `park`.

```
use std::sync::atomic::{AtomicBool, Ordering};
use std:🧵:{current, spawn, park};

static FLAG: AtomicBool = AtomicBool::new(false);

fn main() {
    let thread_0 = current();
    spawn(move || {
        FLAG.store(true, Ordering::Relaxed);
        thread_0.unpark();
    });

    let thread_0 = current();
    spawn(move || {
        thread_0.unpark();
    });

    while !FLAG.load(Ordering::Relaxed) {
        park();
    }
}
```
2018-09-12 18:55:44 +01:00
Ralf Jung
31b63d0ca8 split paragraph 2018-08-28 10:49:45 +02:00
Ralf Jung
34b65db842 document effect of join on memory ordering 2018-08-15 15:22:54 +02:00
Ralf Jung
31bec788f4 avoid using the word 'initialized' to talk about that non-reentrant-capable state of the mutex 2018-08-08 18:12:33 +02:00
Ralf Jung
645388583c actually, reentrant uninitialized mutex acquisition is outright UB 2018-08-06 14:39:55 +02:00
Ralf Jung
d3d31105e9 clarify partially initialized Mutex issues 2018-08-06 12:54:44 +02:00
Pietro Albini
06b91a4901
Rollup merge of #52771 - matklad:patch-1, r=kennytm
Clarify thread::park semantics

It took me quite some time to realize that the example is not actually racy, so let's clarify it? :-)
2018-08-01 10:12:38 +02:00
kennytm
b326319f15
Rollup merge of #52759 - stjepang:impl-send-sync-for-joinhandle, r=TimNN
Impl Send & Sync for JoinHandle

This is just a cosmetic change - it slightly relaxes and clarifies the public API without effectively promising any new guarantees.

Currently we have [these auto trait implementations](https://doc.rust-lang.org/nightly/std/thread/struct.JoinHandle.html#synthetic-implementations):

```rust
impl<T: Send> Send for JoinHandle<T> {}
impl<T: Sync> Sync for JoinHandle<T> {}
```

Bound `T: Send` doesn't make much sense because `JoinHandle<T>` can be created only when `T: Send`. Note that [`JoinHandle::<T>::join`](https://doc.rust-lang.org/nightly/std/thread/struct.JoinHandle.html#method.join) doesn't require `T: Send` so why should the `Send` impl?

And the `Sync` impl doesn't need `T: Sync` because `JoinHandle<T>` cannot even share `T` - it can only send it to the thread that calls `join`.
2018-07-28 16:24:59 +08:00
Aleksey Kladov
5f87f78b14
Fix ws 2018-07-27 14:44:20 +03:00
Aleksey Kladov
922bf1d2ac
Clarify thread::park semantics 2018-07-27 14:01:42 +03:00
Stjepan Glavina
688db1df80 Add stability attributes 2018-07-27 10:08:02 +02:00
Stjepan Glavina
89a81625f4 Impl Send & Sync for JoinHandle 2018-07-27 01:08:13 +02:00
ljedrz
1915cd1dc2 Add missing dyn in tests 2018-07-11 09:11:39 +02:00
ljedrz
560d8079ec Deny bare trait objects in src/libstd. 2018-07-10 20:35:36 +02:00
bors
2eb6969c6a Auto merge of #51290 - Pslydhh:master, r=alexcrichton
park/park_timeout: prohibit spurious wakeups in next park

<pre><code>
// The implementation currently uses the trivial strategy of a Mutex+Condvar
// with wakeup flag, which does not actually allow spurious wakeups.
</pre></code>

Because does not actually allow spurious wakeups.
so we have let thread.inner.cvar.wait(m) in the loop to prohibit spurious wakeups.
but if notified after we locked, this notification doesn't be consumed, it return, the next park will consume this notification...this is also 'spurious wakeup' case, 'one unpark() wakeups two  park()'.

We should improve this situation:
`thread.inner.state.store(EMPTY, SeqCst);`
2018-06-29 07:34:13 +00:00
Michal 'vorner' Vaner
771748d0ba
Fix the error reference for LocalKey::try_with 2018-06-27 07:13:28 +02:00
NODA, Kai
b81da27862 libstd: add an RAII utility for sys_common::mutex::Mutex
Signed-off-by: NODA, Kai <nodakai@gmail.com>
2018-06-17 15:18:32 +08:00
Pslydhh
b352d2d167
removes tabs 2018-06-02 15:59:54 +08:00
Pslydhh
151e41ff0c
remove trailing whitespace
remove trailing whitespace
2018-06-02 15:36:23 +08:00
Pslydhh
7da469da8b
park():prohibit spurious wakeups in next park
should consume this notification, so prohibit spurious wakeups in next park
2018-06-02 14:34:34 +08:00
Alex Crichton
c3a5d6b130 std: Minimize size of panicking on wasm
This commit applies a few code size optimizations for the wasm target to
the standard library, namely around panics. We notably know that in most
configurations it's impossible for us to print anything in
wasm32-unknown-unknown so we can skip larger portions of panicking that
are otherwise simply informative. This allows us to get quite a nice
size reduction.

Finally we can also tweak where the allocation happens for the
`Box<Any>` that we panic with. By only allocating once unwinding starts
we can reduce the size of a panicking wasm module from 44k to 350 bytes.
2018-04-13 07:03:00 -07:00
Stjepan Glavina
cb56b2d152 Fix a bug introduced in previous commit 2018-03-01 00:07:27 +01:00
Stjepan Glavina
27fae2b24a Remove thread_local_state 2018-02-28 18:59:12 +01:00
Stjepan Glavina
c99f4c4c5b Stabilize LocalKey::try_with 2018-02-28 12:41:36 +01:00