format code in tests/ui/threads-sendsync

This commit is contained in:
Tshepang Mbambo 2024-08-24 05:32:52 +02:00
parent 4074d4902d
commit 70ba8c1820
54 changed files with 315 additions and 247 deletions

View File

@ -6,8 +6,8 @@
use std::thread; use std::thread;
fn child2(_s: String) { } fn child2(_s: String) {}
pub fn main() { pub fn main() {
let _x = thread::spawn(move|| child2("hi".to_string())); let _x = thread::spawn(move || child2("hi".to_string()));
} }

View File

@ -7,14 +7,15 @@ use std::thread;
struct Pair { struct Pair {
a: isize, a: isize,
b: isize b: isize,
} }
pub fn main() { pub fn main() {
let z: Box<_> = Box::new(Pair { a : 10, b : 12}); let z: Box<_> = Box::new(Pair { a: 10, b: 12 });
thread::spawn(move|| { thread::spawn(move || {
assert_eq!(z.a, 10); assert_eq!(z.a, 10);
assert_eq!(z.b, 12); assert_eq!(z.b, 12);
}).join(); })
.join();
} }

View File

@ -2,12 +2,12 @@
#![allow(unused_must_use)] #![allow(unused_must_use)]
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() { pub fn main() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let t = thread::spawn(move || { child(&tx) }); let t = thread::spawn(move || child(&tx));
let y = rx.recv().unwrap(); let y = rx.recv().unwrap();
println!("received"); println!("received");
println!("{}", y); println!("{}", y);

View File

@ -2,14 +2,15 @@
//@ needs-threads //@ needs-threads
//@ ignore-sgx no processes //@ ignore-sgx no processes
use std::thread;
use std::env;
use std::process::Command; use std::process::Command;
use std::{env, thread};
struct Handle(i32); struct Handle(i32);
impl Drop for Handle { impl Drop for Handle {
fn drop(&mut self) { panic!(); } fn drop(&mut self) {
panic!();
}
} }
thread_local!(static HANDLE: Handle = Handle(0)); thread_local!(static HANDLE: Handle = Handle(0));
@ -19,14 +20,15 @@ fn main() {
if args.len() == 1 { if args.len() == 1 {
let out = Command::new(&args[0]).arg("test").output().unwrap(); let out = Command::new(&args[0]).arg("test").output().unwrap();
let stderr = std::str::from_utf8(&out.stderr).unwrap(); let stderr = std::str::from_utf8(&out.stderr).unwrap();
assert!(stderr.contains("explicit panic"), assert!(stderr.contains("explicit panic"), "bad failure message:\n{}\n", stderr);
"bad failure message:\n{}\n", stderr);
} else { } else {
// TLS dtors are not always run on process exit // TLS dtors are not always run on process exit
thread::spawn(|| { thread::spawn(|| {
HANDLE.with(|h| { HANDLE.with(|h| {
println!("{}", h.0); println!("{}", h.0);
}); });
}).join().unwrap(); })
.join()
.unwrap();
} }
} }

View File

@ -19,5 +19,7 @@ fn main() {
thread::spawn(|| { thread::spawn(|| {
FOO.with(|_| {}); FOO.with(|_| {});
println!("test1"); println!("test1");
}).join().unwrap(); })
.join()
.unwrap();
} }

View File

@ -9,7 +9,10 @@ pub fn main() {
tx.send("hello, world").unwrap(); tx.send("hello, world").unwrap();
thread::spawn(move|| { thread::spawn(move || {
println!("{}", rx.recv().unwrap()); println!("{}", rx.recv().unwrap());
}).join().ok().unwrap(); })
.join()
.ok()
.unwrap();
} }

View File

@ -7,7 +7,7 @@ use std::thread;
pub fn main() { pub fn main() {
let (tx, rx) = channel::<&'static str>(); let (tx, rx) = channel::<&'static str>();
let t = thread::spawn(move|| { let t = thread::spawn(move || {
assert_eq!(rx.recv().unwrap(), "hello, world"); assert_eq!(rx.recv().unwrap(), "hello, world");
}); });

View File

@ -1,12 +1,12 @@
//@ run-pass //@ run-pass
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::{channel, Receiver}; use std::sync::mpsc::{channel, Receiver};
use std::thread;
fn periodical(n: isize) -> Receiver<bool> { fn periodical(n: isize) -> Receiver<bool> {
let (chan, port) = channel(); let (chan, port) = channel();
thread::spawn(move|| { thread::spawn(move || {
loop { loop {
for _ in 1..n { for _ in 1..n {
match chan.send(false) { match chan.send(false) {
@ -16,7 +16,7 @@ fn periodical(n: isize) -> Receiver<bool> {
} }
match chan.send(true) { match chan.send(true) {
Ok(()) => {} Ok(()) => {}
Err(..) => break Err(..) => break,
} }
} }
}); });
@ -25,7 +25,7 @@ fn periodical(n: isize) -> Receiver<bool> {
fn integers() -> Receiver<isize> { fn integers() -> Receiver<isize> {
let (chan, port) = channel(); let (chan, port) = channel();
thread::spawn(move|| { thread::spawn(move || {
let mut i = 1; let mut i = 1;
loop { loop {
match chan.send(i) { match chan.send(i) {
@ -47,7 +47,7 @@ fn main() {
(_, true, true) => println!("FizzBuzz"), (_, true, true) => println!("FizzBuzz"),
(_, true, false) => println!("Fizz"), (_, true, false) => println!("Fizz"),
(_, false, true) => println!("Buzz"), (_, false, true) => println!("Buzz"),
(i, false, false) => println!("{}", i) (i, false, false) => println!("{}", i),
} }
} }
} }

View File

@ -3,12 +3,12 @@
#![allow(deprecated)] #![allow(deprecated)]
//@ needs-threads //@ needs-threads
use std::sync::mpsc::{TryRecvError, channel}; use std::sync::mpsc::{channel, TryRecvError};
use std::thread; use std::thread;
pub fn main() { pub fn main() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let t = thread::spawn(move||{ let t = thread::spawn(move || {
thread::sleep_ms(10); thread::sleep_ms(10);
tx.send(()).unwrap(); tx.send(()).unwrap();
}); });
@ -16,7 +16,7 @@ pub fn main() {
match rx.try_recv() { match rx.try_recv() {
Ok(()) => break, Ok(()) => break,
Err(TryRecvError::Empty) => {} Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => unreachable!() Err(TryRecvError::Disconnected) => unreachable!(),
} }
} }
t.join(); t.join();

View File

@ -2,18 +2,12 @@
//@ compile-flags:--test //@ compile-flags:--test
//@ needs-threads //@ needs-threads
use std::sync::mpsc::channel; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::TryRecvError; use std::sync::mpsc::{channel, RecvError, RecvTimeoutError, TryRecvError};
use std::sync::mpsc::RecvError;
use std::sync::mpsc::RecvTimeoutError;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
/// Simple thread synchronization utility /// Simple thread synchronization utility
struct Barrier { struct Barrier {
// Not using mutex/condvar for precision // Not using mutex/condvar for precision
@ -42,7 +36,6 @@ impl Barrier {
} }
} }
fn shared_close_sender_does_not_lose_messages_iter() { fn shared_close_sender_does_not_lose_messages_iter() {
let (tb, rb) = Barrier::new2(); let (tb, rb) = Barrier::new2();
@ -71,7 +64,6 @@ fn shared_close_sender_does_not_lose_messages() {
}); });
} }
// https://github.com/rust-lang/rust/issues/39364 // https://github.com/rust-lang/rust/issues/39364
fn concurrent_recv_timeout_and_upgrade_iter() { fn concurrent_recv_timeout_and_upgrade_iter() {
// 1 us // 1 us
@ -85,8 +77,8 @@ fn concurrent_recv_timeout_and_upgrade_iter() {
match rx.recv_timeout(sleep) { match rx.recv_timeout(sleep) {
Ok(_) => { Ok(_) => {
break; break;
}, }
Err(_) => {}, Err(_) => {}
} }
} }
}); });
@ -105,7 +97,6 @@ fn concurrent_recv_timeout_and_upgrade() {
}); });
} }
fn concurrent_writes_iter() { fn concurrent_writes_iter() {
const THREADS: usize = 4; const THREADS: usize = 4;
const PER_THR: usize = 100; const PER_THR: usize = 100;

View File

@ -1,12 +1,13 @@
//@ run-pass //@ run-pass
#![allow(unused_imports)] #![allow(unused_imports)]
use std::thread;
use std::sync::Mutex; use std::sync::Mutex;
use std::thread;
fn par_for<I, F>(iter: I, f: F) fn par_for<I, F>(iter: I, f: F)
where I: Iterator, where
I::Item: Send, I: Iterator,
F: Fn(I::Item) + Sync I::Item: Send,
F: Fn(I::Item) + Sync,
{ {
for item in iter { for item in iter {
f(item) f(item)
@ -15,9 +16,7 @@ fn par_for<I, F>(iter: I, f: F)
fn sum(x: &[i32]) { fn sum(x: &[i32]) {
let sum_lengths = Mutex::new(0); let sum_lengths = Mutex::new(0);
par_for(x.windows(4), |x| { par_for(x.windows(4), |x| *sum_lengths.lock().unwrap() += x.len());
*sum_lengths.lock().unwrap() += x.len()
});
assert_eq!(*sum_lengths.lock().unwrap(), (x.len() - 3) * 4); assert_eq!(*sum_lengths.lock().unwrap(), (x.len() - 3) * 4);
} }
@ -26,9 +25,7 @@ fn main() {
let mut elements = [0; 20]; let mut elements = [0; 20];
// iterators over references into this stack frame // iterators over references into this stack frame
par_for(elements.iter_mut().enumerate(), |(i, x)| { par_for(elements.iter_mut().enumerate(), |(i, x)| *x = i as i32);
*x = i as i32
});
sum(&elements) sum(&elements)
} }

View File

@ -6,11 +6,11 @@
//@ pretty-expanded FIXME #23616 //@ pretty-expanded FIXME #23616
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use std::thread;
struct test { struct test {
f: isize, f: isize,
} }
impl Drop for test { impl Drop for test {
@ -18,15 +18,13 @@ impl Drop for test {
} }
fn test(f: isize) -> test { fn test(f: isize) -> test {
test { test { f: f }
f: f
}
} }
pub fn main() { pub fn main() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let t = thread::spawn(move|| { let t = thread::spawn(move || {
let (tx2, rx2) = channel(); let (tx2, rx2) = channel();
tx.send(tx2).unwrap(); tx.send(tx2).unwrap();

View File

@ -9,11 +9,11 @@ use std::sync::mpsc::{channel, Sender};
// tests that ctrl's type gets inferred properly // tests that ctrl's type gets inferred properly
struct Command<K, V> { struct Command<K, V> {
key: K, key: K,
val: V val: V,
} }
fn cache_server<K:Send+'static,V:Send+'static>(mut tx: Sender<Sender<Command<K, V>>>) { fn cache_server<K: Send + 'static, V: Send + 'static>(mut tx: Sender<Sender<Command<K, V>>>) {
let (tx1, _rx) = channel(); let (tx1, _rx) = channel();
tx.send(tx1); tx.send(tx1);
} }
pub fn main() { } pub fn main() {}

View File

@ -1,9 +1,7 @@
//@ run-pass //@ run-pass
use std::collections::HashMap;
use std::borrow::Cow; use std::borrow::Cow;
use std::borrow::Cow::{Borrowed as B, Owned as O};
use std::borrow::Cow::Borrowed as B; use std::collections::HashMap;
use std::borrow::Cow::Owned as O;
type SendStr = Cow<'static, str>; type SendStr = Cow<'static, str>;

View File

@ -1,8 +1,7 @@
//@ run-pass //@ run-pass
use std::collections::BTreeMap;
use std::borrow::Cow; use std::borrow::Cow;
use std::borrow::Cow::{Borrowed as B, Owned as O};
use std::borrow::Cow::{Owned as O, Borrowed as B}; use std::collections::BTreeMap;
type SendStr = Cow<'static, str>; type SendStr = Cow<'static, str>;
@ -51,8 +50,8 @@ fn main() {
assert_eq!(map.get(&O("def".to_string())), Some(&d)); assert_eq!(map.get(&O("def".to_string())), Some(&d));
assert!(map.remove(&B("foo")).is_some()); assert!(map.remove(&B("foo")).is_some());
assert_eq!(map.into_iter().map(|(k, v)| format!("{}{}", k, v)) assert_eq!(
.collect::<Vec<String>>() map.into_iter().map(|(k, v)| format!("{}{}", k, v)).collect::<Vec<String>>().concat(),
.concat(), "abc50bcd51cde52def53".to_string()
"abc50bcd51cde52def53".to_string()); );
} }

View File

@ -11,15 +11,12 @@
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
struct foo { struct foo {
i: isize, i: isize,
j: char, j: char,
} }
fn foo(i:isize, j: char) -> foo { fn foo(i: isize, j: char) -> foo {
foo { foo { i: i, j: j }
i: i,
j: j
}
} }
pub fn main() { pub fn main() {

View File

@ -1,7 +1,9 @@
//@ run-pass //@ run-pass
fn test<F>(f: F) -> usize
fn test<F>(f: F) -> usize where F: FnOnce(usize) -> usize { where
F: FnOnce(usize) -> usize,
{
return f(22); return f(22);
} }

View File

@ -3,19 +3,24 @@
use std::thread; use std::thread;
pub fn main() { test05(); } pub fn main() {
test05();
}
fn test05_start<F:FnOnce(isize)>(f: F) { fn test05_start<F: FnOnce(isize)>(f: F) {
f(22); f(22);
} }
fn test05() { fn test05() {
let three: Box<_> = Box::new(3); let three: Box<_> = Box::new(3);
let fn_to_send = move|n:isize| { let fn_to_send = move |n: isize| {
println!("{}", *three + n); // will copy x into the closure println!("{}", *three + n); // will copy x into the closure
assert_eq!(*three, 3); assert_eq!(*three, 3);
}; };
thread::spawn(move|| { thread::spawn(move || {
test05_start(fn_to_send); test05_start(fn_to_send);
}).join().ok().unwrap(); })
.join()
.ok()
.unwrap();
} }

View File

@ -10,9 +10,9 @@ fn x(s: String, n: isize) {
} }
pub fn main() { pub fn main() {
let t1 = thread::spawn(|| x("hello from first spawned fn".to_string(), 65) ); let t1 = thread::spawn(|| x("hello from first spawned fn".to_string(), 65));
let t2 = thread::spawn(|| x("hello from second spawned fn".to_string(), 66) ); let t2 = thread::spawn(|| x("hello from second spawned fn".to_string(), 66));
let t3 = thread::spawn(|| x("hello from third spawned fn".to_string(), 67) ); let t3 = thread::spawn(|| x("hello from third spawned fn".to_string(), 67));
let mut i = 30; let mut i = 30;
while i > 0 { while i > 0 {
i = i - 1; i = i - 1;

View File

@ -4,13 +4,13 @@
//@ needs-threads //@ needs-threads
/* /*
Make sure we can spawn tasks that take different types of Make sure we can spawn tasks that take different types of
parameters. This is based on a test case for #520 provided by Rob parameters. This is based on a test case for #520 provided by Rob
Arnold. Arnold.
*/ */
use std::thread;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::thread;
type ctx = Sender<isize>; type ctx = Sender<isize>;
@ -20,6 +20,6 @@ fn iotask(_tx: &ctx, ip: String) {
pub fn main() { pub fn main() {
let (tx, _rx) = channel::<isize>(); let (tx, _rx) = channel::<isize>();
let t = thread::spawn(move|| iotask(&tx, "localhost".to_string()) ); let t = thread::spawn(move || iotask(&tx, "localhost".to_string()));
t.join().ok().unwrap(); t.join().ok().unwrap();
} }

View File

@ -4,7 +4,10 @@
use std::thread; use std::thread;
pub fn main() { pub fn main() {
thread::spawn(move|| child(10)).join().ok().unwrap(); thread::spawn(move || child(10)).join().ok().unwrap();
} }
fn child(i: isize) { println!("{}", i); assert_eq!(i, 10); } fn child(i: isize) {
println!("{}", i);
assert_eq!(i, 10);
}

View File

@ -4,7 +4,7 @@
use std::thread; use std::thread;
pub fn main() { pub fn main() {
let t = thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) ); let t = thread::spawn(move || child((10, 20, 30, 40, 50, 60, 70, 80, 90)));
t.join().ok().unwrap(); // forget Err value, since it doesn't implement Debug t.join().ok().unwrap(); // forget Err value, since it doesn't implement Debug
} }

View File

@ -6,8 +6,16 @@
use std::net::ToSocketAddrs; use std::net::ToSocketAddrs;
fn is_sync<T>(_: T) where T: Sync {} fn is_sync<T>(_: T)
fn is_send<T>(_: T) where T: Send {} where
T: Sync,
{
}
fn is_send<T>(_: T)
where
T: Send,
{
}
macro_rules! all_sync_send { macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({ ($ctor:expr, $($iter:ident),+) => ({

View File

@ -3,18 +3,20 @@
#![allow(warnings)] #![allow(warnings)]
#![feature(drain, collections_bound, btree_range)] #![feature(drain, collections_bound, btree_range)]
use std::collections::BinaryHeap; use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::collections::{BTreeMap, BTreeSet};
use std::collections::LinkedList;
use std::collections::VecDeque;
use std::collections::HashMap;
use std::collections::HashSet;
use std::mem; use std::mem;
use std::ops::Bound::Included; use std::ops::Bound::Included;
fn is_sync<T>(_: T) where T: Sync {} fn is_sync<T>(_: T)
fn is_send<T>(_: T) where T: Send {} where
T: Sync,
{
}
fn is_send<T>(_: T)
where
T: Send,
{
}
macro_rules! all_sync_send { macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({ ($ctor:expr, $($iter:ident),+) => ({

View File

@ -5,8 +5,16 @@
use std::iter::{empty, once, repeat}; use std::iter::{empty, once, repeat};
fn is_sync<T>(_: T) where T: Sync {} fn is_sync<T>(_: T)
fn is_send<T>(_: T) where T: Send {} where
T: Sync,
{
}
fn is_send<T>(_: T)
where
T: Send,
{
}
macro_rules! all_sync_send { macro_rules! all_sync_send {
($ctor:expr, $iter:ident) => ({ ($ctor:expr, $iter:ident) => ({
@ -43,12 +51,12 @@ macro_rules! all_sync_send_mutable_ref {
} }
macro_rules! is_sync_send { macro_rules! is_sync_send {
($ctor:expr) => ({ ($ctor:expr) => {{
let x = $ctor; let x = $ctor;
is_sync(x); is_sync(x);
let y = $ctor; let y = $ctor;
is_send(y); is_send(y);
}) }};
} }
fn main() { fn main() {
@ -63,24 +71,26 @@ fn main() {
let a = [1]; let a = [1];
let b = [2]; let b = [2];
all_sync_send!(a.iter(), all_sync_send!(
cloned, a.iter(),
cycle, cloned,
chain([2].iter()), cycle,
zip([2].iter()), chain([2].iter()),
map(|_| 1), zip([2].iter()),
filter(|_| true), map(|_| 1),
filter_map(|_| Some(1)), filter(|_| true),
enumerate, filter_map(|_| Some(1)),
peekable, enumerate,
skip_while(|_| true), peekable,
take_while(|_| true), skip_while(|_| true),
skip(1), take_while(|_| true),
take(1), skip(1),
scan(1, |_, _| Some(1)), take(1),
flat_map(|_| b.iter()), scan(1, |_, _| Some(1)),
fuse, flat_map(|_| b.iter()),
inspect(|_| ())); fuse,
inspect(|_| ())
);
is_sync_send!((1..).step_by(2)); is_sync_send!((1..).step_by(2));
is_sync_send!((1..2).step_by(2)); is_sync_send!((1..2).step_by(2));

View File

@ -2,12 +2,14 @@
#![allow(unused_must_use)] #![allow(unused_must_use)]
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() { test05(); } pub fn main() {
test05();
}
fn test05_start(tx : &Sender<isize>) { fn test05_start(tx: &Sender<isize>) {
tx.send(10).unwrap(); tx.send(10).unwrap();
println!("sent 10"); println!("sent 10");
tx.send(20).unwrap(); tx.send(20).unwrap();
@ -18,7 +20,7 @@ fn test05_start(tx : &Sender<isize>) {
fn test05() { fn test05() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let t = thread::spawn(move|| { test05_start(&tx) }); let t = thread::spawn(move || test05_start(&tx));
let mut value: isize = rx.recv().unwrap(); let mut value: isize = rx.recv().unwrap();
println!("{}", value); println!("{}", value);
value = rx.recv().unwrap(); value = rx.recv().unwrap();

View File

@ -4,11 +4,15 @@
use std::thread; use std::thread;
pub fn main() { test00(); } pub fn main() {
test00();
}
fn start() { println!("Started / Finished task."); } fn start() {
println!("Started / Finished task.");
}
fn test00() { fn test00() {
thread::spawn(move|| start() ).join(); thread::spawn(move || start()).join();
println!("Completing."); println!("Completing.");
} }

View File

@ -3,8 +3,8 @@
#![allow(unused_mut)] #![allow(unused_mut)]
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::thread;
fn start(tx: &Sender<Sender<String>>) { fn start(tx: &Sender<Sender<String>>) {
let (tx2, rx) = channel(); let (tx2, rx) = channel();
@ -22,7 +22,7 @@ fn start(tx: &Sender<Sender<String>>) {
pub fn main() { pub fn main() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let child = thread::spawn(move|| { start(&tx) }); let child = thread::spawn(move || start(&tx));
let mut c = rx.recv().unwrap(); let mut c = rx.recv().unwrap();
c.send("A".to_string()).unwrap(); c.send("A".to_string()).unwrap();

View File

@ -13,9 +13,7 @@ fn start(tx: &Sender<Sender<isize>>) {
pub fn main() { pub fn main() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let child = thread::spawn(move|| { let child = thread::spawn(move || start(&tx));
start(&tx)
});
let _tx = rx.recv().unwrap(); let _tx = rx.recv().unwrap();
child.join(); child.join();
} }

View File

@ -5,15 +5,17 @@
use std::thread; use std::thread;
pub fn main() { test00(); } pub fn main() {
test00();
}
fn start(_task_number: isize) { println!("Started / Finished task."); } fn start(_task_number: isize) {
println!("Started / Finished task.");
}
fn test00() { fn test00() {
let i: isize = 0; let i: isize = 0;
let mut result = thread::spawn(move|| { let mut result = thread::spawn(move || start(i));
start(i)
});
// Sleep long enough for the thread to finish. // Sleep long enough for the thread to finish.
let mut i = 0_usize; let mut i = 0_usize;

View File

@ -7,12 +7,15 @@ use std::thread;
fn start(tx: &Sender<isize>, start: isize, number_of_messages: isize) { fn start(tx: &Sender<isize>, start: isize, number_of_messages: isize) {
let mut i: isize = 0; let mut i: isize = 0;
while i< number_of_messages { tx.send(start + i).unwrap(); i += 1; } while i < number_of_messages {
tx.send(start + i).unwrap();
i += 1;
}
} }
pub fn main() { pub fn main() {
println!("Check that we don't deadlock."); println!("Check that we don't deadlock.");
let (tx, rx) = channel(); let (tx, rx) = channel();
let _ = thread::spawn(move|| { start(&tx, 0, 10) }).join(); let _ = thread::spawn(move || start(&tx, 0, 10)).join();
println!("Joined task"); println!("Joined task");
} }

View File

@ -13,7 +13,10 @@ pub fn main() {
while (i > 0) { while (i > 0) {
println!("{}", i); println!("{}", i);
let tx = tx.clone(); let tx = tx.clone();
thread::spawn({let i = i; move|| { child(i, &tx) }}); thread::spawn({
let i = i;
move || child(i, &tx)
});
i = i - 1; i = i - 1;
} }

View File

@ -20,9 +20,7 @@ pub fn main() {
// the child's point of view the receiver may die. We should // the child's point of view the receiver may die. We should
// drop messages on the floor in this case, and not crash! // drop messages on the floor in this case, and not crash!
let (tx, rx) = channel(); let (tx, rx) = channel();
let t = thread::spawn(move|| { let t = thread::spawn(move || start(&tx, 10));
start(&tx, 10)
});
rx.recv(); rx.recv();
t.join(); t.join();
} }

View File

@ -3,15 +3,19 @@
#![allow(unused_parens)] #![allow(unused_parens)]
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
use std::sync::mpsc::channel;
use std::cmp; use std::cmp;
use std::sync::mpsc::channel;
// Tests of ports and channels on various types // Tests of ports and channels on various types
fn test_rec() { fn test_rec() {
struct R {val0: isize, val1: u8, val2: char} struct R {
val0: isize,
val1: u8,
val2: char,
}
let (tx, rx) = channel(); let (tx, rx) = channel();
let r0: R = R {val0: 0, val1: 1, val2: '2'}; let r0: R = R { val0: 0, val1: 1, val2: '2' };
tx.send(r0).unwrap(); tx.send(r0).unwrap();
let mut r1: R; let mut r1: R;
r1 = rx.recv().unwrap(); r1 = rx.recv().unwrap();
@ -45,34 +49,29 @@ fn test_str() {
enum t { enum t {
tag1, tag1,
tag2(isize), tag2(isize),
tag3(isize, u8, char) tag3(isize, u8, char),
} }
impl cmp::PartialEq for t { impl cmp::PartialEq for t {
fn eq(&self, other: &t) -> bool { fn eq(&self, other: &t) -> bool {
match *self { match *self {
t::tag1 => { t::tag1 => match (*other) {
match (*other) { t::tag1 => true,
t::tag1 => true, _ => false,
_ => false },
} t::tag2(e0a) => match (*other) {
} t::tag2(e0b) => e0a == e0b,
t::tag2(e0a) => { _ => false,
match (*other) { },
t::tag2(e0b) => e0a == e0b, t::tag3(e0a, e1a, e2a) => match (*other) {
_ => false t::tag3(e0b, e1b, e2b) => e0a == e0b && e1a == e1b && e2a == e2b,
} _ => false,
} },
t::tag3(e0a, e1a, e2a) => {
match (*other) {
t::tag3(e0b, e1b, e2b) =>
e0a == e0b && e1a == e1b && e2a == e2b,
_ => false
}
}
} }
} }
fn ne(&self, other: &t) -> bool { !(*self).eq(other) } fn ne(&self, other: &t) -> bool {
!(*self).eq(other)
}
} }
fn test_tag() { fn test_tag() {

View File

@ -9,9 +9,8 @@
use std::thread; use std::thread;
fn f() { fn f() {}
}
pub fn main() { pub fn main() {
thread::spawn(move|| f() ).join(); thread::spawn(move || f()).join();
} }

View File

@ -2,10 +2,13 @@
#![allow(unused_must_use)] #![allow(unused_must_use)]
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() { println!("===== WITHOUT THREADS ====="); test00(); } pub fn main() {
println!("===== WITHOUT THREADS =====");
test00();
}
fn test00_start(ch: &Sender<isize>, message: isize, count: isize) { fn test00_start(ch: &Sender<isize>, message: isize, count: isize) {
println!("Starting test00_start"); println!("Starting test00_start");
@ -34,9 +37,7 @@ fn test00() {
let tx = tx.clone(); let tx = tx.clone();
results.push(thread::spawn({ results.push(thread::spawn({
let i = i; let i = i;
move|| { move || test00_start(&tx, i, number_of_messages)
test00_start(&tx, i, number_of_messages)
}
})); }));
i = i + 1; i = i + 1;
} }
@ -53,7 +54,9 @@ fn test00() {
} }
// Join spawned threads... // Join spawned threads...
for r in results { r.join(); } for r in results {
r.join();
}
println!("Completed: Final number is: "); println!("Completed: Final number is: ");
println!("{}", sum); println!("{}", sum);

View File

@ -3,7 +3,9 @@
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
pub fn main() { test00(); } pub fn main() {
test00();
}
fn test00() { fn test00() {
let mut r: isize = 0; let mut r: isize = 0;

View File

@ -2,7 +2,9 @@
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
pub fn main() { test00(); } pub fn main() {
test00();
}
fn test00() { fn test00() {
let _r: isize = 0; let _r: isize = 0;
@ -10,8 +12,14 @@ fn test00() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let number_of_messages: isize = 1000; let number_of_messages: isize = 1000;
let mut i: isize = 0; let mut i: isize = 0;
while i < number_of_messages { tx.send(i + 0).unwrap(); i += 1; } while i < number_of_messages {
tx.send(i + 0).unwrap();
i += 1;
}
i = 0; i = 0;
while i < number_of_messages { sum += rx.recv().unwrap(); i += 1; } while i < number_of_messages {
sum += rx.recv().unwrap();
i += 1;
}
assert_eq!(sum, number_of_messages * (number_of_messages - 1) / 2); assert_eq!(sum, number_of_messages * (number_of_messages - 1) / 2);
} }

View File

@ -4,7 +4,9 @@
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
pub fn main() { test00(); } pub fn main() {
test00();
}
fn test00() { fn test00() {
let mut r: isize = 0; let mut r: isize = 0;
@ -38,5 +40,4 @@ fn test00() {
assert_eq!(sum, 1998000); assert_eq!(sum, 1998000);
// assert (sum == 4 * ((number_of_messages * // assert (sum == 4 * ((number_of_messages *
// (number_of_messages - 1)) / 2)); // (number_of_messages - 1)) / 2));
} }

View File

@ -6,12 +6,16 @@
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::thread; use std::thread;
pub fn main() { test00(); } pub fn main() {
test00();
}
fn test00_start(c: &Sender<isize>, start: isize, fn test00_start(c: &Sender<isize>, start: isize, number_of_messages: isize) {
number_of_messages: isize) {
let mut i: isize = 0; let mut i: isize = 0;
while i < number_of_messages { c.send(start + i).unwrap(); i += 1; } while i < number_of_messages {
c.send(start + i).unwrap();
i += 1;
}
} }
fn test00() { fn test00() {
@ -21,19 +25,19 @@ fn test00() {
let number_of_messages: isize = 10; let number_of_messages: isize = 10;
let tx2 = tx.clone(); let tx2 = tx.clone();
let t1 = thread::spawn(move|| { let t1 = thread::spawn(move || {
test00_start(&tx2, number_of_messages * 0, number_of_messages); test00_start(&tx2, number_of_messages * 0, number_of_messages);
}); });
let tx2 = tx.clone(); let tx2 = tx.clone();
let t2 = thread::spawn(move|| { let t2 = thread::spawn(move || {
test00_start(&tx2, number_of_messages * 1, number_of_messages); test00_start(&tx2, number_of_messages * 1, number_of_messages);
}); });
let tx2 = tx.clone(); let tx2 = tx.clone();
let t3 = thread::spawn(move|| { let t3 = thread::spawn(move || {
test00_start(&tx2, number_of_messages * 2, number_of_messages); test00_start(&tx2, number_of_messages * 2, number_of_messages);
}); });
let tx2 = tx.clone(); let tx2 = tx.clone();
let t4 = thread::spawn(move|| { let t4 = thread::spawn(move || {
test00_start(&tx2, number_of_messages * 3, number_of_messages); test00_start(&tx2, number_of_messages * 3, number_of_messages);
}); });

View File

@ -2,14 +2,19 @@
#![allow(unused_must_use)] #![allow(unused_must_use)]
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() { test00(); } pub fn main() {
test00();
}
fn test00_start(c: &Sender<isize>, number_of_messages: isize) { fn test00_start(c: &Sender<isize>, number_of_messages: isize) {
let mut i: isize = 0; let mut i: isize = 0;
while i < number_of_messages { c.send(i + 0).unwrap(); i += 1; } while i < number_of_messages {
c.send(i + 0).unwrap();
i += 1;
}
} }
fn test00() { fn test00() {
@ -18,7 +23,7 @@ fn test00() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let number_of_messages: isize = 10; let number_of_messages: isize = 10;
let result = thread::spawn(move|| { let result = thread::spawn(move || {
test00_start(&tx, number_of_messages); test00_start(&tx, number_of_messages);
}); });

View File

@ -6,9 +6,7 @@
use std::thread; use std::thread;
pub fn main() { pub fn main() {
thread::spawn(move|| child("Hello".to_string()) ).join(); thread::spawn(move || child("Hello".to_string())).join();
} }
fn child(_s: String) { fn child(_s: String) {}
}

View File

@ -2,8 +2,8 @@
#![allow(unused_must_use)] #![allow(unused_must_use)]
//@ needs-threads //@ needs-threads
use std::thread;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use std::thread;
pub fn main() { pub fn main() {
let (tx, rx) = channel::<usize>(); let (tx, rx) = channel::<usize>();

View File

@ -4,20 +4,21 @@
#![feature(internal_output_capture)] #![feature(internal_output_capture)]
use std::io;
use std::str;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread; use std::{io, str, thread};
fn main() { fn main() {
let data = Arc::new(Mutex::new(Vec::new())); let data = Arc::new(Mutex::new(Vec::new()));
let res = thread::Builder::new().spawn({ let res = thread::Builder::new()
let data = data.clone(); .spawn({
move || { let data = data.clone();
io::set_output_capture(Some(data)); move || {
panic!("Hello, world!") io::set_output_capture(Some(data));
} panic!("Hello, world!")
}).unwrap().join(); }
})
.unwrap()
.join();
assert!(res.is_err()); assert!(res.is_err());
let output = data.lock().unwrap(); let output = data.lock().unwrap();

View File

@ -8,14 +8,14 @@ use std::io::prelude::*;
use std::net::{TcpListener, TcpStream}; use std::net::{TcpListener, TcpStream};
use std::process; use std::process;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use std::time::Duration;
use std::thread::{self, Builder}; use std::thread::{self, Builder};
use std::time::Duration;
const TARGET_CNT: usize = 200; const TARGET_CNT: usize = 200;
fn main() { fn main() {
// This test has a chance to time out, try to not let it time out // This test has a chance to time out, try to not let it time out
thread::spawn(move|| -> () { thread::spawn(move || -> () {
thread::sleep(Duration::from_secs(30)); thread::sleep(Duration::from_secs(30));
process::exit(1); process::exit(1);
}); });
@ -38,12 +38,12 @@ fn main() {
let mut spawned_cnt = 0; let mut spawned_cnt = 0;
for _ in 0..TARGET_CNT { for _ in 0..TARGET_CNT {
let tx = tx.clone(); let tx = tx.clone();
let res = Builder::new().stack_size(64 * 1024).spawn(move|| { let res = Builder::new().stack_size(64 * 1024).spawn(move || {
match TcpStream::connect(addr) { match TcpStream::connect(addr) {
Ok(mut stream) => { Ok(mut stream) => {
let _ = stream.write(&[1]); let _ = stream.write(&[1]);
let _ = stream.read(&mut [0]); let _ = stream.read(&mut [0]);
}, }
Err(..) => {} Err(..) => {}
} }
tx.send(()).unwrap(); tx.send(()).unwrap();

View File

@ -7,10 +7,16 @@ use std::thread;
pub fn main() { pub fn main() {
let mut i = 10; let mut i = 10;
while i > 0 { while i > 0 {
thread::spawn({let i = i; move|| child(i)}).join(); thread::spawn({
let i = i;
move || child(i)
})
.join();
i = i - 1; i = i - 1;
} }
println!("main thread exiting"); println!("main thread exiting");
} }
fn child(x: isize) { println!("{}", x); } fn child(x: isize) {
println!("{}", x);
}

View File

@ -8,7 +8,9 @@ struct Foo;
impl Drop for Foo { impl Drop for Foo {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { HIT = true; } unsafe {
HIT = true;
}
} }
} }
@ -17,6 +19,8 @@ thread_local!(static FOO: Foo = Foo);
fn main() { fn main() {
std::thread::spawn(|| { std::thread::spawn(|| {
FOO.with(|_| {}); FOO.with(|_| {});
}).join().unwrap(); })
.join()
.unwrap();
assert!(unsafe { HIT }); assert!(unsafe { HIT });
} }

View File

@ -1,14 +1,14 @@
//@ run-pass //@ run-pass
#![allow(stable_features)] #![allow(stable_features)]
//@ needs-threads //@ needs-threads
#![feature(thread_local_try_with)] #![feature(thread_local_try_with)]
use std::thread;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
struct Foo { cnt: usize } struct Foo {
cnt: usize,
}
thread_local!(static FOO: Foo = Foo::init()); thread_local!(static FOO: Foo = Foo::init());
@ -40,5 +40,7 @@ impl Drop for Foo {
fn main() { fn main() {
thread::spawn(|| { thread::spawn(|| {
FOO.with(|_| {}); FOO.with(|_| {});
}).join().unwrap(); })
.join()
.unwrap();
} }

View File

@ -1,8 +1,6 @@
//@ run-pass //@ run-pass
#![allow(stable_features)] #![allow(stable_features)]
//@ needs-threads //@ needs-threads
#![feature(thread_local_try_with)] #![feature(thread_local_try_with)]
use std::thread; use std::thread;
@ -16,15 +14,17 @@ thread_local!(static FOO: Foo = Foo {});
impl Drop for Foo { impl Drop for Foo {
fn drop(&mut self) { fn drop(&mut self) {
assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err()); assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err());
unsafe { DROP_RUN = true; } unsafe {
DROP_RUN = true;
}
} }
} }
fn main() { fn main() {
thread::spawn(|| { thread::spawn(|| {
assert_eq!(FOO.try_with(|_| { assert_eq!(FOO.try_with(|_| { 132 }).expect("`try_with` failed"), 132);
132 })
}).expect("`try_with` failed"), 132); .join()
}).join().unwrap(); .unwrap();
assert!(unsafe { DROP_RUN }); assert!(unsafe { DROP_RUN });
} }

View File

@ -2,9 +2,9 @@
#![allow(unused_must_use)] #![allow(unused_must_use)]
/* /*
This is about the simplest program that can successfully send a This is about the simplest program that can successfully send a
message. message.
*/ */
use std::sync::mpsc::channel; use std::sync::mpsc::channel;

View File

@ -21,9 +21,7 @@ impl Drop for complainer {
fn complainer(tx: Sender<bool>) -> complainer { fn complainer(tx: Sender<bool>) -> complainer {
println!("Hello!"); println!("Hello!");
complainer { complainer { tx: tx }
tx: tx
}
} }
fn f(tx: Sender<bool>) { fn f(tx: Sender<bool>) {
@ -33,7 +31,7 @@ fn f(tx: Sender<bool>) {
pub fn main() { pub fn main() {
let (tx, rx) = channel(); let (tx, rx) = channel();
let t = thread::spawn(move|| f(tx.clone())); let t = thread::spawn(move || f(tx.clone()));
println!("hiiiiiiiii"); println!("hiiiiiiiii");
assert!(rx.recv().unwrap()); assert!(rx.recv().unwrap());
drop(t.join()); drop(t.join());

View File

@ -17,5 +17,9 @@ pub fn main() {
} }
fn child() { fn child() {
println!("4"); thread::yield_now(); println!("5"); thread::yield_now(); println!("6"); println!("4");
thread::yield_now();
println!("5");
thread::yield_now();
println!("6");
} }

View File

@ -13,4 +13,6 @@ pub fn main() {
result.join(); result.join();
} }
fn child() { println!("2"); } fn child() {
println!("2");
}

View File

@ -4,5 +4,9 @@ use std::thread;
pub fn main() { pub fn main() {
let mut i: isize = 0; let mut i: isize = 0;
while i < 100 { i = i + 1; println!("{}", i); thread::yield_now(); } while i < 100 {
i = i + 1;
println!("{}", i);
thread::yield_now();
}
} }