├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md ├── benches └── benches.rs ├── examples └── simple.rs ├── src ├── fiber │ ├── back.rs │ ├── front.rs │ ├── mod.rs │ └── worker.rs ├── fnbox.rs ├── lib.rs ├── task.rs └── thread │ ├── back.rs │ └── mod.rs └── tests └── tests.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.o 3 | *.so 4 | *.rlib 5 | *.dll 6 | 7 | # Executables 8 | *.exe 9 | 10 | # Generated by Cargo 11 | /target/ 12 | /Cargo.lock 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - nightly 4 | 5 | script: 6 | - cargo test 7 | - cargo test --features fiber --no-default-features -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fibe" 3 | version = "0.3.0" 4 | license = "Apache-2.0" 5 | keywords = ["gamedev"] 6 | authors = ["Fibe-rs Hackers"] 7 | 8 | [lib] 9 | name = "fibe" 10 | 11 | [features] 12 | default = ["thread"] 13 | thread = [] 14 | fiber = ["bran", "deque"] 15 | 16 | [dependencies] 17 | log = "*" 18 | atom = "*" 19 | rand = "*" 20 | num_cpus = "*" 21 | libc = "*" 22 | 23 | [dependencies.pulse] 24 | features = ["callback"] 25 | 26 | [dependencies.deque] 27 | git = "https://github.com/csherratt/deque.git" 28 | optional = true 29 | 30 | [dependencies.bran] 31 | git = "https://github.com/slide-rs/bran.git" 32 | optional = true 33 | 34 | [dependencies.future_pulse] 35 | git = "https://github.com/slide-rs/future_pulse.git" 36 | 37 | [dev-dependencies] 38 | timebomb = "*" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/slide-rs/fibe-rs.png?branch=master)](https://travis-ci.org/slide-rs/fibe-rs) 2 | 3 | ### Fiberized task queue in Rust 4 | 5 | It is currently very generic and simple. Each task is given an unique handle, and other tasks can use it to specify their dependencies. A task only executes when all dependencies are finished. Any sharing or passing of the data between tasks is user's problem. May the channels help him/her. 6 | 7 | The implementation can be further expanded by introducing thread pools or fibers without affecting the interface. 8 | 9 | The idea is to see how far this design can go when used in a game. Dog-fooding results will then determine the evolution vector or the termination of this humble experiment. 10 | -------------------------------------------------------------------------------- /benches/benches.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | 3 | extern crate fibe; 4 | extern crate test; 5 | extern crate pulse; 6 | extern crate future_pulse; 7 | 8 | use fibe::*; 9 | use test::Bencher; 10 | use pulse::Signals; 11 | use future_pulse::Future; 12 | 13 | fn warmup(front: &mut fibe::Frontend) { 14 | for _ in 0..100 { 15 | task(|_| {}).start(front); 16 | } 17 | task(|_| {}).start(front).get(); 18 | } 19 | 20 | #[bench] 21 | fn start_die(b: &mut Bencher) { 22 | b.iter(|| { 23 | let front = fibe::Frontend::new(); 24 | front.die(fibe::Wait::None); 25 | }); 26 | } 27 | 28 | #[bench] 29 | fn chain_10_use_die(b: &mut Bencher) { 30 | b.iter(|| { 31 | let mut front = fibe::Frontend::new(); 32 | let mut last = task(move |_| {}).start(&mut front); 33 | for _ in 1..10 { 34 | last = task(move |_| {}).after(last.signal()).start(&mut front); 35 | } 36 | front.die(fibe::Wait::Pending); 37 | }); 38 | } 39 | 40 | #[bench] 41 | fn chain_10_wait(b: &mut Bencher) { 42 | let mut front = fibe::Frontend::new(); 43 | warmup(&mut front); 44 | b.iter(|| { 45 | let mut last = task(move |_| {}).start(&mut front); 46 | for _ in 1..10 { 47 | last = task(move |_| {}).after(last.signal()).start(&mut front); 48 | } 49 | last.wait().unwrap(); 50 | }); 51 | } 52 | 53 | #[bench] 54 | fn chain_1_000_use_die(b: &mut Bencher) { 55 | b.iter(|| { 56 | let mut front = fibe::Frontend::new(); 57 | let mut last = task(move |_| {}).start(&mut front); 58 | for _ in 1..1_000 { 59 | last = task(move |_| {}).after(last.signal()).start(&mut front); 60 | } 61 | front.die(fibe::Wait::Pending); 62 | }); 63 | } 64 | 65 | #[bench] 66 | fn chain_1_000_wait(b: &mut Bencher) { 67 | let mut front = fibe::Frontend::new(); 68 | warmup(&mut front); 69 | b.iter(|| { 70 | let mut last = task(move |_| {}).start(&mut front); 71 | for _ in 1..1_000 { 72 | last = task(move |_| {}).after(last.signal()).start(&mut front); 73 | } 74 | last.wait().unwrap(); 75 | }); 76 | } 77 | 78 | 79 | fn fibb_steal(depth: usize, front: &mut fibe::Frontend) -> Future { 80 | let task = task(move |_| {1}); 81 | if depth == 0 { 82 | task 83 | } else { 84 | let left = fibb_steal(depth - 1, front); 85 | let right = fibb_steal(depth - 1, front); 86 | task.after(left.signal()).after(right.signal()) 87 | }.start(front) 88 | } 89 | 90 | #[bench] 91 | fn bench_fibb_steal(b: &mut Bencher) { 92 | let mut front = fibe::Frontend::new(); 93 | warmup(&mut front); 94 | b.iter(|| { 95 | fibb_steal(8, &mut front).wait().unwrap(); 96 | }); 97 | } 98 | 99 | #[bench] 100 | fn fanout_1_000(b: &mut Bencher) { 101 | let mut front = fibe::Frontend::new(); 102 | warmup(&mut front); 103 | b.iter(|| { 104 | let (signal, pulse) = pulse::Signal::new(); 105 | let signals: Vec = (0..1_000).map(|_| 106 | task(move |_| {}).after(signal.clone()).start(&mut front).signal() 107 | ).collect(); 108 | pulse.pulse(); 109 | pulse::Barrier::new(&signals).wait().unwrap(); 110 | }); 111 | } 112 | 113 | /* 114 | struct Repeater(usize); 115 | 116 | impl ResumableTask for Repeater { 117 | #[inline(never)] 118 | fn resume(&mut self, _: &mut Schedule) -> WaitState { 119 | self.0 -= 1; 120 | if self.0 == 0 { 121 | WaitState::Completed 122 | } else { 123 | WaitState::Pending(pulse::Signal::pulsed()) 124 | } 125 | } 126 | } 127 | 128 | #[bench] 129 | fn repeat_1_000(b: &mut Bencher) { 130 | let mut front = fibe::Frontend::new(); 131 | b.iter(|| { 132 | Repeater(1_000).start(&mut front).wait().unwrap(); 133 | }); 134 | } 135 | 136 | #[bench] 137 | fn repeat_100_x_100(b: &mut Bencher) { 138 | let mut front = fibe::Frontend::new(); 139 | b.iter(|| { 140 | let signals: Vec = (0..100).map(|_| 141 | Repeater(100).start(&mut front) 142 | ).collect(); 143 | pulse::Barrier::new(&signals).wait().unwrap(); 144 | }); 145 | } 146 | 147 | #[bench] 148 | fn repeat_1_000_x_1_000(b: &mut Bencher) { 149 | let mut front = fibe::Frontend::new(); 150 | b.iter(|| { 151 | let signals: Vec = (0..1_000).map(|_| 152 | Repeater(1_000).start(&mut front) 153 | ).collect(); 154 | pulse::Barrier::new(&signals).wait().unwrap(); 155 | }); 156 | } 157 | */ 158 | 159 | #[bench] 160 | fn chain_10_fibers(b: &mut Bencher) { 161 | let mut front = Frontend::new(); 162 | warmup(&mut front); 163 | b.iter(|| { 164 | let (mut s, p) = Future::new(); 165 | for _ in 0..10 { 166 | s = task(|_| s.get()).start(&mut front); 167 | } 168 | p.set(()); 169 | s.get(); 170 | }); 171 | } 172 | 173 | #[bench] 174 | fn spawn(b: &mut Bencher) { 175 | let mut front = Frontend::new(); 176 | warmup(&mut front); 177 | 178 | b.iter(|| { 179 | task(|_| {}).start(&mut front).get(); 180 | }); 181 | } 182 | 183 | #[bench] 184 | fn spawn_get(b: &mut Bencher) { 185 | let mut front = Frontend::new(); 186 | warmup(&mut front); 187 | 188 | b.iter(|| { 189 | task(|_| {}).start(&mut front); 190 | }); 191 | } -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | extern crate fibe; 2 | extern crate pulse; 3 | 4 | use fibe::*; 5 | use pulse::Signals; 6 | 7 | fn test(wait: Wait) { 8 | let mut front = Frontend::new(); 9 | let ha = task(move |_| {print!("Hello, ")}).start(&mut front); 10 | task(move |_| {println!("World!")}).after(ha.signal()).start(&mut front); 11 | front.die(wait); 12 | } 13 | 14 | fn main() { 15 | test(Wait::None); 16 | test(Wait::Active); 17 | test(Wait::Pending); 18 | } 19 | -------------------------------------------------------------------------------- /src/fiber/back.rs: -------------------------------------------------------------------------------- 1 | //! Back-end module for the task queue. The back-end is running 2 | //! on a separate thread. All it does is listening to a command 3 | //! channel and starting new tasks when the time comes. 4 | 5 | use std::sync::atomic::*; 6 | use std::sync::{Arc, Mutex}; 7 | use std::sync::mpsc::{Sender, Receiver, channel}; 8 | use std::collections::HashMap; 9 | use std::thread; 10 | 11 | use bran; 12 | use pulse::*; 13 | use deque; 14 | use num_cpus; 15 | 16 | use {Wait, Schedule, FnBox}; 17 | use super::worker; 18 | 19 | struct Inner { 20 | index: usize, 21 | stealers: HashMap>, 22 | workers: HashMap>, 23 | joins: Vec> 24 | } 25 | 26 | /// Task queue back-end. 27 | pub struct Backend { 28 | active: AtomicBool, 29 | global_queue: Mutex>, 30 | workers: Mutex, 31 | pool: bran::StackPool 32 | } 33 | 34 | /// A ready task 35 | pub struct ReadyTask(bran::Handle); 36 | 37 | impl ReadyTask { 38 | pub fn run(self) { 39 | use bran::fiber::State; 40 | let ReadyTask(task) = self; 41 | match task.run() { 42 | State::Pending(signal) => { 43 | worker::requeue(task, signal); 44 | } 45 | State::PendingTimeout(_, _) => { 46 | panic!("Timeouts are not supported") 47 | } 48 | State::Finished | State::Panicked => () 49 | } 50 | } 51 | } 52 | 53 | impl Backend { 54 | /// Create a new back-end. 55 | pub fn new() -> Arc { 56 | let buffer = deque::BufferPool::new(); 57 | let (worker, stealer) = buffer.deque(); 58 | 59 | let mut map = HashMap::new(); 60 | map.insert(0, stealer); 61 | 62 | let back = Arc::new(Backend { 63 | active: AtomicBool::new(false), 64 | global_queue: Mutex::new(worker), 65 | workers: Mutex::new(Inner { 66 | index: 1, 67 | stealers: map, 68 | workers: HashMap::new(), 69 | joins: Vec::new() 70 | }), 71 | pool: bran::StackPool::new() 72 | }); 73 | 74 | for _ in 0..num_cpus::get() { 75 | worker::Worker::new(back.clone()).start(); 76 | } 77 | back 78 | } 79 | 80 | /// Start a task on the global work queue 81 | fn start_on_global_queue(&self, rt: ReadyTask) { 82 | let guard = self.global_queue.lock().unwrap(); 83 | guard.push(rt); 84 | } 85 | 86 | /// Start a task that will run once all the Handle's have 87 | /// been completed. 88 | pub fn start(back: Arc, task: Box, mut after: Vec) { 89 | // Create the wait signal if needed 90 | let signal = if after.len() == 0 { 91 | Signal::pulsed() 92 | } else if after.len() == 1 { 93 | after.pop().unwrap() 94 | } else { 95 | Barrier::new(&after).signal() 96 | }; 97 | 98 | signal.callback(move || { 99 | if !back.active.load(Ordering::SeqCst) { 100 | let fiber = bran::fiber::Fiber::spawn_with(move || { 101 | task.call_box(&mut worker::FiberSchedule) 102 | }, back.pool.clone()); 103 | let try_thread = worker::start(ReadyTask(fiber)); 104 | match try_thread { 105 | Ok(b) => b, 106 | Err(rt) => { 107 | back.start_on_global_queue(rt); 108 | true 109 | } 110 | }; 111 | } 112 | }); 113 | } 114 | 115 | /// Start a task that will run once all the Handle's have 116 | /// been completed. 117 | pub fn enqueue(back: Arc, task: bran::Handle, after: Signal) { 118 | after.callback(move || { 119 | if !back.active.load(Ordering::SeqCst) { 120 | let try_thread = worker::start(ReadyTask(task)); 121 | match try_thread { 122 | Ok(b) => b, 123 | Err(rt) => { 124 | back.start_on_global_queue(rt); 125 | true 126 | } 127 | }; 128 | } 129 | }); 130 | } 131 | 132 | /// Kill the backend, wait until the condition is satisfied. 133 | pub fn exit(&self, wait: Wait) { 134 | // read the current active count, OR in the BLOCK 135 | // flag if needed for the wait 136 | match wait { 137 | Wait::None | Wait::Active => { 138 | self.active.store(true, Ordering::SeqCst); 139 | } 140 | Wait::Pending => () 141 | }; 142 | 143 | let mut guard = self.workers.lock().unwrap(); 144 | for (_, send) in guard.workers.iter() { 145 | let _ = send.send(worker::Command::Exit); 146 | } 147 | 148 | while let Some(join) = guard.joins.pop() { 149 | join.join().unwrap(); 150 | } 151 | } 152 | 153 | /// Create a new deque 154 | pub fn new_deque(&self) -> (usize, 155 | deque::Worker, 156 | Receiver) { 157 | 158 | let buffer = deque::BufferPool::new(); 159 | let (worker, stealer) = buffer.deque(); 160 | let (send, recv) = channel(); 161 | let mut guard = self.workers.lock().unwrap(); 162 | let index = guard.index; 163 | guard.index += 1; 164 | for (&key, stealer) in guard.stealers.iter() { 165 | send.send(worker::Command::Add(key, stealer.clone())).unwrap(); 166 | } 167 | for (_, workers) in guard.workers.iter() { 168 | workers.send(worker::Command::Add(index, stealer.clone())).unwrap(); 169 | } 170 | guard.stealers.insert(index, stealer); 171 | guard.workers.insert(index, send); 172 | (index, worker, recv) 173 | } 174 | 175 | /// 176 | pub fn register_worker(&self, handle: thread::JoinHandle<()>) { 177 | let mut guard = self.workers.lock().unwrap(); 178 | guard.joins.push(handle); 179 | } 180 | } 181 | 182 | impl<'a> Schedule for Arc { 183 | fn add_task(&mut self, task: Box, after: Vec) { 184 | Backend::start(self.clone(), task, after) 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/fiber/front.rs: -------------------------------------------------------------------------------- 1 | //! Front-end module for the task queue. The front-end exists 2 | //! on the user side, allowing to add more tasks to the queue. 3 | 4 | use std::sync::Arc; 5 | use pulse::Signal; 6 | 7 | use super::back::Backend; 8 | use {Wait, Schedule, FnBox}; 9 | 10 | /// Queue front-end. 11 | pub struct Frontend { 12 | backend: Arc, 13 | } 14 | 15 | impl Frontend { 16 | /// Create a new front-end with an associated 17 | /// back-end automatically. 18 | pub fn new() -> Frontend { 19 | let backend = Backend::new(); 20 | let back = backend.clone(); 21 | let front = Frontend { 22 | backend: back, 23 | }; 24 | front 25 | } 26 | 27 | /// Stop the queue, using selected wait mode. 28 | pub fn die(self, wait: Wait) -> bool { 29 | self.backend.exit(wait); 30 | true 31 | } 32 | } 33 | 34 | impl Drop for Frontend { 35 | fn drop(&mut self) { 36 | self.backend.exit(Wait::None) 37 | } 38 | } 39 | 40 | impl Schedule for Frontend { 41 | fn add_task(&mut self, task: Box, after: Vec) { 42 | Backend::start(self.backend.clone(), task, after) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/fiber/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod back; 2 | pub mod front; 3 | pub mod worker; -------------------------------------------------------------------------------- /src/fiber/worker.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::cell::RefCell; 3 | use std::sync::Arc; 4 | use std::thread; 5 | use std::sync::mpsc::Receiver; 6 | use std::thread::sleep_ms; 7 | 8 | use pulse::Signal; 9 | use rand::{self, Rng}; 10 | use deque::{self, Stolen}; 11 | use super::back::{Backend, ReadyTask}; 12 | use Schedule; 13 | use bran; 14 | 15 | use FnBox; 16 | 17 | pub enum Command { 18 | Add(usize, deque::Stealer), 19 | Exit 20 | } 21 | 22 | thread_local!(static WORKER: RefCell> = RefCell::new(None)); 23 | 24 | pub struct Worker { 25 | index: usize, 26 | back: Arc, 27 | queue: deque::Worker, 28 | command: Option> 29 | } 30 | 31 | impl Worker { 32 | pub fn new(back: Arc) -> Worker { 33 | let (index, worker, rx) = back.new_deque(); 34 | 35 | Worker { 36 | back: back, 37 | index: index, 38 | queue: worker, 39 | command: Some(rx) 40 | } 41 | } 42 | 43 | pub fn start(self) { 44 | let name = format!("Worker {}", self.index); 45 | let back = self.back.clone(); 46 | let guard = thread::Builder::new().name(name).spawn(move || { 47 | WORKER.with(|worker| { 48 | *worker.borrow_mut() = Some(self); 49 | }); 50 | work(); 51 | }).unwrap(); 52 | 53 | back.register_worker(guard); 54 | } 55 | } 56 | 57 | #[inline(never)] 58 | fn work() { 59 | WORKER.with(|worker| { 60 | let cmd = worker.borrow_mut().as_mut().unwrap().command.take().unwrap(); 61 | 62 | let mut rand = rand::XorShiftRng::new_unseeded(); 63 | let mut stealers: Vec<(usize, deque::Stealer)> = Vec::new(); 64 | 65 | let mut i = 0; 66 | let mut run = true; 67 | let mut backoff = 0; 68 | 69 | while run { 70 | // Try to grab form our own queue 71 | if let Some(task) = worker.borrow().as_ref().unwrap().queue.pop() { 72 | task.run(); 73 | i = 0; 74 | backoff = 0; 75 | continue; 76 | } 77 | 78 | while run { 79 | i += 1; 80 | 81 | // Try to grab from one of the stealers 82 | if stealers.len() > 0 { 83 | let x: usize = rand.gen(); 84 | let x = x % stealers.len(); 85 | if let Stolen::Data(task) = stealers[x].1.steal() { 86 | task.run(); 87 | i = 0; 88 | backoff = 0; 89 | break; 90 | } 91 | } 92 | 93 | // Try to go to sleep 94 | if i >= stealers.len() * 2 { 95 | while let Ok(msg) = cmd.try_recv() { 96 | match msg { 97 | Command::Add(key, value) => { 98 | stealers.push((key, value)); 99 | } 100 | Command::Exit => { 101 | run = false; 102 | } 103 | } 104 | i = 0; 105 | } 106 | 107 | if i != 0 { 108 | backoff += 1; 109 | sleep_ms(backoff); 110 | i = stealers.len(); 111 | } 112 | } 113 | } 114 | } 115 | }); 116 | } 117 | 118 | // Use the task on the TLS queue or the queue in the backend 119 | #[inline] 120 | pub fn start(rt: ReadyTask) -> Result { 121 | WORKER.with(|worker| { 122 | if let Some(worker) = worker.borrow().as_ref() { 123 | worker.queue.push(rt); 124 | Ok(true) 125 | } else { 126 | Err(rt) 127 | } 128 | }) 129 | } 130 | 131 | /// used for fibers to give them child task spawning 132 | pub struct FiberSchedule; 133 | 134 | impl Schedule for FiberSchedule { 135 | fn add_task(&mut self, task: Box, after: Vec) { 136 | let back = WORKER.with(|worker| { 137 | worker.borrow() 138 | .as_ref() 139 | .expect("a fiber was resumed outside of a worker") 140 | .back.clone() 141 | }); 142 | Backend::start(back, task, after) 143 | } 144 | } 145 | 146 | pub fn requeue(task: bran::Handle, after: Signal) { 147 | let back = WORKER.with(|worker| { 148 | worker.borrow() 149 | .as_ref() 150 | .expect("a fiber was resumed outside of a worker") 151 | .back.clone() 152 | }); 153 | Backend::enqueue(back, task, after) 154 | } -------------------------------------------------------------------------------- /src/fnbox.rs: -------------------------------------------------------------------------------- 1 | use Schedule; 2 | 3 | /// A simple version of fnbox found in libstd 4 | pub trait FnBox { 5 | /// Call the box consomuming the fnbox 6 | fn call_box(self: Box, sched: &mut Schedule); 7 | } 8 | 9 | impl FnBox for F { 10 | fn call_box(self: Box, sched: &mut Schedule) { 11 | (*self)(sched) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![deny(missing_docs)] 2 | 3 | //! A simple task queue with dependency tracking. 4 | 5 | #[macro_use] 6 | extern crate log; 7 | extern crate pulse; 8 | extern crate atom; 9 | 10 | extern crate rand; 11 | extern crate libc; 12 | extern crate num_cpus; 13 | 14 | #[cfg(feature="fiber")] 15 | extern crate deque; 16 | 17 | #[cfg(feature="fiber")] 18 | extern crate bran; 19 | 20 | extern crate future_pulse; 21 | 22 | #[cfg(feature="fiber")] 23 | mod fiber; 24 | 25 | #[cfg(feature="thread")] 26 | mod thread; 27 | 28 | mod task; 29 | mod fnbox; 30 | 31 | #[cfg(feature="fiber")] 32 | pub use fiber::front::Frontend; 33 | 34 | #[cfg(feature="thread")] 35 | pub use thread::Frontend; 36 | 37 | 38 | use pulse::Signal; 39 | 40 | pub use fnbox::FnBox; 41 | pub use self::task::{task, TaskBuilder}; 42 | 43 | /// Wait mode for the front-end termination. 44 | #[derive(PartialEq, Copy, Clone, Debug)] 45 | pub enum Wait { 46 | /// Wait for nothing - terminate immediately. 47 | None, 48 | /// Wait for active tasks only, drop the pending. 49 | Active, 50 | /// Wait for the whole queue to flush. 51 | Pending, 52 | } 53 | 54 | /// Abstract representation of a the scheduler, allow for new tasks 55 | /// to be created and enqueued. 56 | pub trait Schedule { 57 | /// Add a new task with selected dependencies. This doesn't interrupt any 58 | /// tasks in-flight. The task will actually start as soon as all 59 | /// dependencies are finished. 60 | fn add_task(&mut self, task: Box, after: Vec); 61 | } 62 | -------------------------------------------------------------------------------- /src/task.rs: -------------------------------------------------------------------------------- 1 | 2 | use pulse::Signal; 3 | use future_pulse::Future; 4 | use {Schedule, FnBox}; 5 | 6 | /// A structure to help build a task 7 | pub struct TaskBuilder { 8 | /// The task to be run 9 | task: Box, 10 | 11 | /// The signals to wait on 12 | wait: Vec, 13 | 14 | /// The results 15 | result: Future 16 | } 17 | 18 | impl TaskBuilder { 19 | /// Start the task only after `signal` is asserted 20 | pub fn after(mut self, signal: Signal) -> TaskBuilder { 21 | self.wait.push(signal); 22 | self 23 | } 24 | 25 | /// Start the task using the supplied scheduler 26 | pub fn start(self, sched: &mut Schedule) -> Future { 27 | let TaskBuilder{task, wait, result} = self; 28 | sched.add_task(task, wait); 29 | result 30 | } 31 | } 32 | 33 | /// Create a fiber 34 | pub fn task(f: F) -> TaskBuilder 35 | where F: FnOnce(&mut Schedule) -> T + Send + 'static { 36 | 37 | let (future, set) = Future::new(); 38 | TaskBuilder { 39 | task: Box::new(move |sched: &mut Schedule| { 40 | set.set(f(sched)); 41 | }), 42 | wait: Vec::new(), 43 | result: future 44 | } 45 | } -------------------------------------------------------------------------------- /src/thread/back.rs: -------------------------------------------------------------------------------- 1 | //! Back-end module for the task queue. The back-end is running 2 | //! on a separate thread. All it does is listening to a command 3 | //! channel and starting new tasks when the time comes. 4 | 5 | use std::sync::{Arc, Mutex}; 6 | use std::thread; 7 | 8 | use pulse::*; 9 | 10 | use {Wait, Schedule, FnBox}; 11 | 12 | /// Task queue back-end. 13 | pub struct Inner { 14 | shutdown: bool, 15 | running: usize, 16 | wake: Option 17 | } 18 | 19 | pub struct Backend(Mutex); 20 | 21 | impl Backend { 22 | /// Create a new back-end. 23 | pub fn new() -> Arc { 24 | Arc::new(Backend(Mutex::new(Inner{ 25 | shutdown: false, 26 | running: 0, 27 | wake: None 28 | }))) 29 | } 30 | 31 | /// Start a task that will run once all the Handle's have 32 | /// been completed. 33 | pub fn start(back: Arc, task: Box, mut after: Vec) { 34 | // Create the wait signal if needed 35 | let signal = if after.len() == 0 { 36 | Signal::pulsed() 37 | } else if after.len() == 1 { 38 | after.pop().unwrap() 39 | } else { 40 | Barrier::new(&after).signal() 41 | }; 42 | 43 | signal.callback(move || { 44 | let mut g = back.0.lock().unwrap(); 45 | if !g.shutdown { 46 | let b = back.clone(); 47 | thread::spawn(move || { 48 | let mut b = b; 49 | task.call_box(&mut b); 50 | let mut g = b.0.lock().unwrap(); 51 | g.running -= 1; 52 | if g.running == 0 { 53 | g.wake.take().map(|p| p.pulse()); 54 | } 55 | }); 56 | g.running += 1; 57 | } 58 | }); 59 | } 60 | 61 | /// Kill the backend, wait until the condition is satisfied. 62 | pub fn exit(&self, wait: Wait) { 63 | let mut g = self.0.lock().unwrap(); 64 | 65 | // read the current active count, OR in the BLOCK 66 | // flag if needed for the wait 67 | match wait { 68 | Wait::None | Wait::Active => { 69 | g.shutdown = true; 70 | } 71 | Wait::Pending => () 72 | }; 73 | 74 | if g.running != 0 { 75 | let (p, t) = Signal::new(); 76 | g.wake = Some(t); 77 | drop(g); 78 | p.wait().unwrap(); 79 | } 80 | } 81 | } 82 | 83 | impl<'a> Schedule for Arc { 84 | fn add_task(&mut self, task: Box, after: Vec) { 85 | Backend::start(self.clone(), task, after) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/thread/mod.rs: -------------------------------------------------------------------------------- 1 | //! Front-end module for the task queue. The front-end exists 2 | //! on the user side, allowing to add more tasks to the queue. 3 | 4 | mod back; 5 | 6 | use std::sync::Arc; 7 | use pulse::Signal; 8 | 9 | use self::back::Backend; 10 | use {Wait, Schedule, FnBox}; 11 | 12 | /// Queue front-end. 13 | pub struct Frontend { 14 | backend: Arc, 15 | } 16 | 17 | impl Frontend { 18 | /// Create a new front-end with an associated 19 | /// back-end automatically. 20 | pub fn new() -> Frontend { 21 | let backend = Backend::new(); 22 | let back = backend.clone(); 23 | let front = Frontend { 24 | backend: back, 25 | }; 26 | front 27 | } 28 | 29 | /// Stop the queue, using selected wait mode. 30 | pub fn die(self, wait: Wait) -> bool { 31 | self.backend.exit(wait); 32 | true 33 | } 34 | } 35 | 36 | impl Drop for Frontend { 37 | fn drop(&mut self) { 38 | self.backend.exit(Wait::None) 39 | } 40 | } 41 | 42 | impl Schedule for Frontend { 43 | fn add_task(&mut self, task: Box, after: Vec) { 44 | Backend::start(self.backend.clone(), task, after) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/tests.rs: -------------------------------------------------------------------------------- 1 | extern crate fibe; 2 | extern crate timebomb; 3 | extern crate pulse; 4 | extern crate future_pulse; 5 | 6 | use fibe::*; 7 | use pulse::Signals; 8 | use future_pulse::Future; 9 | use timebomb::timeout_ms; 10 | 11 | #[test] 12 | fn die_empty_none() { 13 | timeout_ms(|| { 14 | let front = Frontend::new(); 15 | front.die(fibe::Wait::None); 16 | }, 3000); 17 | } 18 | 19 | #[test] 20 | fn die_empty_pending() { 21 | timeout_ms(|| { 22 | let front = Frontend::new(); 23 | front.die(fibe::Wait::Pending); 24 | }, 3000); 25 | } 26 | 27 | #[test] 28 | fn die_empty_active() { 29 | timeout_ms(|| { 30 | let front = Frontend::new(); 31 | front.die(fibe::Wait::Active); 32 | }, 3000); 33 | } 34 | 35 | #[test] 36 | fn die_all_active_none() { 37 | timeout_ms(|| { 38 | let mut front = Frontend::new(); 39 | for _ in 0..10 { 40 | task(move |_| {}).start(&mut front); 41 | } 42 | front.die(fibe::Wait::None); 43 | }, 3000); 44 | } 45 | 46 | #[test] 47 | fn die_all_active_pending() { 48 | timeout_ms(|| { 49 | let mut front = Frontend::new(); 50 | for _ in 0..10 { 51 | task(move |_| {}).start(&mut front); 52 | } 53 | front.die(fibe::Wait::Pending); 54 | }, 3000); 55 | } 56 | 57 | #[test] 58 | fn die_all_active_active() { 59 | timeout_ms(|| { 60 | let mut front = Frontend::new(); 61 | for _ in 0..10 { 62 | task(move |_| {}).start(&mut front); 63 | } 64 | front.die(fibe::Wait::Active); 65 | }, 3000); 66 | } 67 | 68 | #[test] 69 | fn die_pending_chain_none() { 70 | timeout_ms(|| { 71 | let mut front = Frontend::new(); 72 | let mut last = task(move |_| {}).start(&mut front); 73 | for _ in 1..10 { 74 | last = task(move |_| {}) 75 | .after(last.signal()) 76 | .start(&mut front); 77 | } 78 | front.die(fibe::Wait::None); 79 | }, 3000); 80 | } 81 | 82 | #[test] 83 | fn die_pending_chain_pending() { 84 | timeout_ms(|| { 85 | let mut front = Frontend::new(); 86 | let mut last = task(move |_| {}).start(&mut front); 87 | for _ in 1..10 { 88 | last = task(move |_| {}).after(last.signal()).start(&mut front); 89 | } 90 | front.die(fibe::Wait::Pending); 91 | }, 3000); 92 | } 93 | 94 | #[test] 95 | fn die_pending_chain_active() { 96 | timeout_ms(|| { 97 | let mut front = Frontend::new(); 98 | let mut last = task(move |_| {}).start(&mut front); 99 | for _ in 1..10 { 100 | last = task(move |_| {}) 101 | .after(last.signal()) 102 | .start(&mut front); 103 | } 104 | front.die(fibe::Wait::Active); 105 | }, 3000); 106 | } 107 | 108 | #[test] 109 | fn spawn_child() { 110 | timeout_ms(|| { 111 | let mut front = Frontend::new(); 112 | let last = task(move |s| { 113 | let a = task(move |_| {}).start(s); 114 | let b = task(move |_| {}).start(s); 115 | a.wait().unwrap(); 116 | b.wait().unwrap(); 117 | }).start(&mut front); 118 | last.wait().unwrap(); 119 | }, 3000); 120 | } 121 | 122 | /* 123 | struct CountDown(u32, Sender<()>); 124 | 125 | impl Drop for CountDown { 126 | fn drop(&mut self) { 127 | self.1.send(()).unwrap(); 128 | assert!(self.0 == 0); 129 | } 130 | } 131 | 132 | impl ResumableTask for CountDown { 133 | fn resume(&mut self, sched: &mut Schedule) -> WaitState { 134 | if self.0 == 0 { 135 | WaitState::Completed 136 | } else { 137 | self.0 -= 1; 138 | WaitState::Pending( 139 | task(move |_| {}).start(sched) 140 | ) 141 | } 142 | } 143 | } 144 | 145 | #[test] 146 | fn resumeable_task() { 147 | timeout_ms(|| { 148 | let mut front = Frontend::new(); 149 | let (tx, rx) = channel(); 150 | let count = CountDown(1000, tx); 151 | count.start(&mut front).wait().unwrap(); 152 | rx.try_recv().ok().expect("Task should have sent an ack"); 153 | }, 3000); 154 | } 155 | */ 156 | 157 | #[test] 158 | fn fiber_test() { 159 | timeout_ms(|| { 160 | let mut front = Frontend::new(); 161 | let (s0, p0) = pulse::Signal::new(); 162 | let (s1, p1) = pulse::Signal::new(); 163 | task(|_| { 164 | s0.wait().unwrap(); 165 | p1.pulse(); 166 | }).start(&mut front); 167 | 168 | assert!(s1.is_pending()); 169 | p0.pulse(); 170 | s1.wait().unwrap(); 171 | }, 3000); 172 | } 173 | 174 | 175 | #[test] 176 | fn fiber_test_1k() { 177 | timeout_ms(|| { 178 | let mut front = Frontend::new(); 179 | let (mut future, set) = Future::new(); 180 | for _ in 0..1_000 { 181 | future = task(|_| future.get() + 1).start(&mut front); 182 | } 183 | set.set(0); 184 | assert_eq!(future.get(), 1_000); 185 | }, 3000); 186 | } --------------------------------------------------------------------------------