-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy paththreads.rs
536 lines (422 loc) · 12.5 KB
/
threads.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use crossbeam::thread as crossbeam_thread;
use go_spawn::{go, join};
use parking::Parker;
use rayon;
use send_wrapper::SendWrapper;
use thread_amount::thread_amount;
use thread_control::*;
use thread_priority::*;
use scopeguard::{guard, defer,defer_on_unwind, defer_on_success};
#[cfg(not(target_os = "macos"))]
use affinity::*;
pub fn start_one_thread() {
let count = thread::available_parallelism().unwrap().get();
println!("available_parallelism: {}", count);
let handle = thread::spawn(|| {
println!("Hello from a thread!");
});
handle.join().unwrap();
}
pub fn start_one_thread_result() {
let handle = thread::spawn(|| {
println!("Hello from a thread!");
200
});
match handle.join() {
Ok(v) => println!("thread result: {}", v),
Err(e) => println!("error: {:?}", e),
}
}
pub fn start_two_threads() {
let handle1 = thread::spawn(|| {
println!("Hello from a thread1!");
});
let handle2 = thread::spawn(|| {
println!("Hello from a thread2!");
});
handle1.join().unwrap();
handle2.join().unwrap();
}
pub fn start_n_threads() {
const N: isize = 10;
let handles: Vec<_> = (0..N)
.map(|i| {
thread::spawn(move || {
println!("Hello from a thread{}!", i);
})
})
.collect();
// handles.into_iter().for_each(|h| h.join().unwrap());
for handle in handles {
handle.join().unwrap();
}
}
pub fn current_thread() {
let current_thread = thread::current();
println!(
"current thread: {:?},{:?}",
current_thread.id(),
current_thread.name()
);
let builder = thread::Builder::new()
.name("foo".into()) // set thread name
.stack_size(32 * 1024); // set stack size
let handler = builder
.spawn(|| {
let current_thread = thread::current();
println!(
"child thread: {:?},{:?}",
current_thread.id(),
current_thread.name()
);
})
.unwrap();
handler.join().unwrap();
}
pub fn start_thread_with_sleep() {
let handle1 = thread::spawn(|| {
thread::sleep(Duration::from_millis(2000));
println!("Hello from a thread3!");
});
let handle2 = thread::spawn(|| {
thread::sleep(Duration::from_millis(1000));
println!("Hello from a thread4!");
});
handle1.join().unwrap();
handle2.join().unwrap();
}
pub fn start_thread_with_yield_now() {
let handle1 = thread::spawn(|| {
thread::yield_now();
println!("yield_now!");
});
let handle2 = thread::spawn(|| {
thread::yield_now();
println!("yield_now in another thread!");
});
handle1.join().unwrap();
handle2.join().unwrap();
}
pub fn start_thread_with_priority() {
let handle1 = thread::spawn(|| {
assert!(set_current_thread_priority(ThreadPriority::Min).is_ok());
println!("Hello from a thread5!");
});
let handle2 = thread::spawn(|| {
assert!(set_current_thread_priority(ThreadPriority::Max).is_ok());
println!("Hello from a thread6!");
});
handle1.join().unwrap();
handle2.join().unwrap();
}
pub fn thread_builder() {
let thread1 = ThreadBuilder::default()
.name("MyThread")
.priority(ThreadPriority::Max)
.spawn(|result| {
println!("Set priority result: {:?}", result);
assert!(result.is_ok());
})
.unwrap();
let thread2 = ThreadBuilder::default()
.name("MyThread")
.priority(ThreadPriority::Max)
.spawn_careless(|| {
println!("We don't care about the priority result.");
})
.unwrap();
thread1.join().unwrap();
thread2.join().unwrap();
}
pub fn start_one_thread_with_move() {
let x = 100;
let handle = thread::spawn(move || {
println!("Hello from a thread with move, x={}!", x);
});
handle.join().unwrap();
let handle = thread::spawn(move || {
println!("Hello from a thread with move again, x={}!", x);
});
handle.join().unwrap();
let handle = thread::spawn(|| {
println!("Hello from a thread without move");
});
handle.join().unwrap();
}
// pub fn start_one_thread_with_move2() {
// let x = vec![1, 2, 3];
// let handle = thread::spawn(move || {
// println!("Hello from a thread with move, x={:?}!", x);
// });
// handle.join().unwrap();
// let handle = thread::spawn(move|| {
// println!("Hello from a thread with move again, x={:?}!", x);
// });
// handle.join().unwrap();
// let handle = thread::spawn(|| {
// println!("Hello from a thread without move");
// });
// handle.join().unwrap();
// }
pub fn start_threads_with_threadlocal() {
thread_local!(static COUNTER: RefCell<u32> = RefCell::new(1));
COUNTER.with(|c| {
*c.borrow_mut() = 2;
});
let handle1 = thread::spawn(move || {
COUNTER.with(|c| {
*c.borrow_mut() = 3;
});
COUNTER.with(|c| {
println!("Hello from a thread7, c={}!", *c.borrow());
});
});
let handle2 = thread::spawn(move || {
COUNTER.with(|c| {
*c.borrow_mut() = 4;
});
COUNTER.with(|c| {
println!("Hello from a thread8, c={}!", *c.borrow());
});
});
handle1.join().unwrap();
handle2.join().unwrap();
COUNTER.with(|c| {
println!("Hello from main, c={}!", *c.borrow());
});
}
pub fn thread_park() {
let handle = thread::spawn(|| {
thread::park();
println!("Hello from a park thread!");
});
thread::sleep(Duration::from_millis(1000));
handle.thread().unpark();
handle.join().unwrap();
}
pub fn thread_park2() {
let handle = thread::spawn(|| {
thread::sleep(Duration::from_millis(1000));
thread::park();
println!("Hello from a park thread in case of unpark first!");
});
handle.thread().unpark();
handle.join().unwrap();
}
pub fn thread_park_timeout() {
let handle = thread::spawn(|| {
thread::park_timeout(Duration::from_millis(1000));
println!("Hello from a park_timeout thread!");
});
handle.join().unwrap();
}
// pub fn wrong_start_threads_without_scoped() {
// let mut a = vec![1, 2, 3];
// let mut x = 0;
// thread::spawn(move || {
// println!("hello from the first scoped thread");
// dbg!(&a);
// });
// thread::spawn(move || {
// println!("hello from the second scoped thread");
// x += a[0] + a[2];
// });
// println!("hello from the main thread");
// // After the scope, we can modify and access our variables again:
// a.push(4);
// assert_eq!(x, a.len());
// }
pub fn start_scoped_threads() {
let mut a = vec![1, 2, 3];
let mut x = 0;
thread::scope(|s| {
s.spawn(|| {
println!("hello from the first scoped thread");
dbg!(&a);
});
s.spawn(|| {
println!("hello from the second scoped thread");
x += a[0] + a[2];
});
println!("hello from the main thread");
});
// After the scope, we can modify and access our variables again:
a.push(4);
assert_eq!(x, a.len());
}
pub fn crossbeam_scope() {
let mut a = vec![1, 2, 3];
let mut x = 0;
crossbeam_thread::scope(|s| {
s.spawn(|_| {
println!("hello from the first crossbeam scoped thread");
dbg!(&a);
});
s.spawn(|_| {
println!("hello from the second crossbeam scoped thread");
x += a[0] + a[2];
});
println!("hello from the main thread");
})
.unwrap();
// After the scope, we can modify and access our variables again:
a.push(4);
assert_eq!(x, a.len());
}
pub fn rayon_scope() {
let mut a = vec![1, 2, 3];
let mut x = 0;
rayon::scope(|s| {
s.spawn(|_| {
println!("hello from the first rayon scoped thread");
dbg!(&a);
});
s.spawn(|_| {
println!("hello from the second rayon scoped thread");
x += a[0] + a[2];
});
println!("hello from the main thread");
});
// After the scope, we can modify and access our variables again:
a.push(4);
assert_eq!(x, a.len());
}
// pub fn wrong_send() {
// let counter = Rc::new(42);
// let (sender, receiver) = channel();
// let _t = thread::spawn(move || {
// sender.send(counter).unwrap();
// });
// let value = receiver.recv().unwrap();
// println!("received from the main thread: {}", value);
// }
pub fn send_wrapper() {
let wrapped_value = SendWrapper::new(Rc::new(42));
let (sender, receiver) = channel();
let _t = thread::spawn(move || {
sender.send(wrapped_value).unwrap();
});
let wrapped_value = receiver.recv().unwrap();
let value = wrapped_value.deref();
println!("received from the main thread: {}", value);
}
pub fn print_thread_amount() {
let mut handles = vec![];
for _ in 1..=10 {
let amount = thread_amount();
let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(1000));
if !amount.is_none() {
println!("thread amount: {}", amount.unwrap());
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
pub fn control_thread() {
let (flag, control) = make_pair();
let handle = thread::spawn(move || {
while flag.alive() {
thread::sleep(Duration::from_millis(100));
println!("I'm alive!");
}
});
thread::sleep(Duration::from_millis(100));
assert_eq!(control.is_done(), false);
control.stop(); // Also you can `control.interrupt()` it
handle.join().unwrap();
assert_eq!(control.is_interrupted(), false);
assert_eq!(control.is_done(), true);
println!("This thread is stopped")
}
#[cfg(not(target_os = "macos"))]
pub fn use_affinity() {
// Select every second core
let cores: Vec<usize> = (0..get_core_num()).step_by(2).collect();
println!("Binding thread to cores : {:?}", &cores);
affinity::set_thread_affinity(&cores).unwrap();
println!(
"Current thread affinity : {:?}",
affinity::get_thread_affinity().unwrap()
);
}
fn foo() {
println!("foo");
}
pub fn go_thread() {
let counter = Arc::new(AtomicI64::new(0));
let counter_cloned = counter.clone();
// Spawn a thread that captures values by move.
go! {
for _ in 0..100 {
counter_cloned.fetch_add(1, Ordering::SeqCst);
}
}
go!(foo());
// Join the most recent thread spawned by `go_spawn` that has not yet been joined.
assert!(join!().is_ok());
assert_eq!(counter.load(Ordering::SeqCst), 100);
}
pub fn park_thread() {
let p = Parker::new();
let u = p.unparker();
// Notify the parker.
u.unpark();
// Wakes up immediately because the parker is notified.
p.park();
thread::spawn(move || {
thread::sleep(Duration::from_millis(500));
u.unpark();
});
// Wakes up when `u.unpark()` notifies and then goes back into unnotified state.
p.park();
println!("park_unpark")
}
pub fn info() {
let count = thread::available_parallelism().unwrap().get();
println!("available_parallelism: {}", count);
if let Some(count) = num_threads::num_threads() {
println!("num_threads: {}", count);
} else {
println!("num_threads: not supported");
}
let count = thread_amount::thread_amount();
if !count.is_none() {
println!("thread_amount: {}", count.unwrap());
}
let count = num_cpus::get();
println!("num_cpus: {}", count);
}
pub fn scopeguard_defer() {
defer! {
println!("scopeguard: Called at return or panic");
}
println!("scopeguard: Called first before panic");
// panic!();
println!("scopeguard: Called first after panic");
}
macro_rules! join_all {
($($x:ident),*) => {
$($x.join().unwrap();)*
}
}
pub fn join_all_example() {
let handle1 = thread::spawn(|| {
println!("Hello from a thread1!");
});
let handle2 = thread::spawn(|| {
println!("Hello from a thread2!");
});
join_all!(handle1,handle2);
}