]> git.lizzy.rs Git - rust.git/blob - src/libgreen/lib.rs
Rename all raw pointers as necessary
[rust.git] / src / libgreen / lib.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The "green scheduling" library
12 //!
13 //! This library provides M:N threading for rust programs. Internally this has
14 //! the implementation of a green scheduler along with context switching and a
15 //! stack-allocation strategy. This can be optionally linked in to rust
16 //! programs in order to provide M:N functionality inside of 1:1 programs.
17 //!
18 //! # Architecture
19 //!
20 //! An M:N scheduling library implies that there are N OS thread upon which M
21 //! "green threads" are multiplexed. In other words, a set of green threads are
22 //! all run inside a pool of OS threads.
23 //!
24 //! With this design, you can achieve _concurrency_ by spawning many green
25 //! threads, and you can achieve _parallelism_ by running the green threads
26 //! simultaneously on multiple OS threads. Each OS thread is a candidate for
27 //! being scheduled on a different core (the source of parallelism), and then
28 //! all of the green threads cooperatively schedule amongst one another (the
29 //! source of concurrency).
30 //!
31 //! ## Schedulers
32 //!
33 //! In order to coordinate among green threads, each OS thread is primarily
34 //! running something which we call a Scheduler. Whenever a reference to a
35 //! Scheduler is made, it is synonymous to referencing one OS thread. Each
36 //! scheduler is bound to one and exactly one OS thread, and the thread that it
37 //! is bound to never changes.
38 //!
39 //! Each scheduler is connected to a pool of other schedulers (a `SchedPool`)
40 //! which is the thread pool term from above. A pool of schedulers all share the
41 //! work that they create. Furthermore, whenever a green thread is created (also
42 //! synonymously referred to as a green task), it is associated with a
43 //! `SchedPool` forevermore. A green thread cannot leave its scheduler pool.
44 //!
45 //! Schedulers can have at most one green thread running on them at a time. When
46 //! a scheduler is asleep on its event loop, there are no green tasks running on
47 //! the OS thread or the scheduler. The term "context switch" is used for when
48 //! the running green thread is swapped out, but this simply changes the one
49 //! green thread which is running on the scheduler.
50 //!
51 //! ## Green Threads
52 //!
53 //! A green thread can largely be summarized by a stack and a register context.
54 //! Whenever a green thread is spawned, it allocates a stack, and then prepares
55 //! a register context for execution. The green task may be executed across
56 //! multiple OS threads, but it will always use the same stack and it will carry
57 //! its register context across OS threads.
58 //!
59 //! Each green thread is cooperatively scheduled with other green threads.
60 //! Primarily, this means that there is no pre-emption of a green thread. The
61 //! major consequence of this design is that a green thread stuck in an infinite
62 //! loop will prevent all other green threads from running on that particular
63 //! scheduler.
64 //!
65 //! Scheduling events for green threads occur on communication and I/O
66 //! boundaries. For example, if a green task blocks waiting for a message on a
67 //! channel some other green thread can now run on the scheduler. This also has
68 //! the consequence that until a green thread performs any form of scheduling
69 //! event, it will be running on the same OS thread (unconditionally).
70 //!
71 //! ## Work Stealing
72 //!
73 //! With a pool of schedulers, a new green task has a number of options when
74 //! deciding where to run initially. The current implementation uses a concept
75 //! called work stealing in order to spread out work among schedulers.
76 //!
77 //! In a work-stealing model, each scheduler maintains a local queue of tasks to
78 //! run, and this queue is stolen from by other schedulers. Implementation-wise,
79 //! work stealing has some hairy parts, but from a user-perspective, work
80 //! stealing simply implies what with M green threads and N schedulers where
81 //! M > N it is very likely that all schedulers will be busy executing work.
82 //!
83 //! # Considerations when using libgreen
84 //!
85 //! An M:N runtime has both pros and cons, and there is no one answer as to
86 //! whether M:N or 1:1 is appropriate to use. As always, there are many
87 //! advantages and disadvantages between the two. Regardless of the workload,
88 //! however, there are some aspects of using green thread which you should be
89 //! aware of:
90 //!
91 //! * The largest concern when using libgreen is interoperating with native
92 //!   code. Care should be taken when calling native code that will block the OS
93 //!   thread as it will prevent further green tasks from being scheduled on the
94 //!   OS thread.
95 //!
96 //! * Native code using thread-local-storage should be approached
97 //!   with care. Green threads may migrate among OS threads at any time, so
98 //!   native libraries using thread-local state may not always work.
99 //!
100 //! * Native synchronization primitives (e.g. pthread mutexes) will also not
101 //!   work for green threads. The reason for this is because native primitives
102 //!   often operate on a _os thread_ granularity whereas green threads are
103 //!   operating on a more granular unit of work.
104 //!
105 //! * A green threading runtime is not fork-safe. If the process forks(), it
106 //!   cannot expect to make reasonable progress by continuing to use green
107 //!   threads.
108 //!
109 //! Note that these concerns do not mean that operating with native code is a
110 //! lost cause. These are simply just concerns which should be considered when
111 //! invoking native code.
112 //!
113 //! # Starting with libgreen
114 //!
115 //! ```rust
116 //! extern crate green;
117 //!
118 //! #[start]
119 //! fn start(argc: int, argv: *const *const u8) -> int {
120 //!     green::start(argc, argv, green::basic::event_loop, main)
121 //! }
122 //!
123 //! fn main() {
124 //!     // this code is running in a pool of schedulers
125 //! }
126 //! ```
127 //!
128 //! > **Note**: This `main` function in this example does *not* have I/O
129 //! >           support. The basic event loop does not provide any support
130 //!
131 //! # Starting with I/O support in libgreen
132 //!
133 //! ```rust
134 //! extern crate green;
135 //! extern crate rustuv;
136 //!
137 //! #[start]
138 //! fn start(argc: int, argv: *const *const u8) -> int {
139 //!     green::start(argc, argv, rustuv::event_loop, main)
140 //! }
141 //!
142 //! fn main() {
143 //!     // this code is running in a pool of schedulers all powered by libuv
144 //! }
145 //! ```
146 //!
147 //! The above code can also be shortened with a macro from libgreen.
148 //!
149 //! ```
150 //! #![feature(phase)]
151 //! #[phase(plugin)] extern crate green;
152 //!
153 //! green_start!(main)
154 //!
155 //! fn main() {
156 //!     // run inside of a green pool
157 //! }
158 //! ```
159 //!
160 //! # Using a scheduler pool
161 //!
162 //! This library adds a `GreenTaskBuilder` trait that extends the methods
163 //! available on `std::task::TaskBuilder` to allow spawning a green task,
164 //! possibly pinned to a particular scheduler thread:
165 //!
166 //! ```rust
167 //! use std::task::TaskBuilder;
168 //! use green::{SchedPool, PoolConfig, GreenTaskBuilder};
169 //!
170 //! let config = PoolConfig::new();
171 //! let mut pool = SchedPool::new(config);
172 //!
173 //! // Spawn tasks into the pool of schedulers
174 //! TaskBuilder::new().green(&mut pool).spawn(proc() {
175 //!     // this code is running inside the pool of schedulers
176 //!
177 //!     spawn(proc() {
178 //!         // this code is also running inside the same scheduler pool
179 //!     });
180 //! });
181 //!
182 //! // Dynamically add a new scheduler to the scheduler pool. This adds another
183 //! // OS thread that green threads can be multiplexed on to.
184 //! let mut handle = pool.spawn_sched();
185 //!
186 //! // Pin a task to the spawned scheduler
187 //! TaskBuilder::new().green_pinned(&mut pool, &mut handle).spawn(proc() {
188 //!     /* ... */
189 //! });
190 //!
191 //! // Handles keep schedulers alive, so be sure to drop all handles before
192 //! // destroying the sched pool
193 //! drop(handle);
194 //!
195 //! // Required to shut down this scheduler pool.
196 //! // The task will fail if `shutdown` is not called.
197 //! pool.shutdown();
198 //! ```
199
200 #![crate_id = "green#0.11.0-pre"]
201 #![experimental]
202 #![license = "MIT/ASL2"]
203 #![crate_type = "rlib"]
204 #![crate_type = "dylib"]
205 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
206        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
207        html_root_url = "http://doc.rust-lang.org/",
208        html_playground_url = "http://play.rust-lang.org/")]
209
210 // NB this does *not* include globs, please keep it that way.
211 #![feature(macro_rules, phase)]
212 #![allow(visible_private_types)]
213 #![allow(deprecated)]
214 #![feature(default_type_params)]
215
216 #[cfg(test)] #[phase(plugin, link)] extern crate log;
217 #[cfg(test)] extern crate rustuv;
218 extern crate libc;
219 extern crate alloc;
220
221 use alloc::arc::Arc;
222 use std::mem::replace;
223 use std::os;
224 use std::rt::rtio;
225 use std::rt::thread::Thread;
226 use std::rt::task::TaskOpts;
227 use std::rt;
228 use std::sync::atomics::{SeqCst, AtomicUint, INIT_ATOMIC_UINT};
229 use std::sync::deque;
230 use std::task::{TaskBuilder, Spawner};
231
232 use sched::{Shutdown, Scheduler, SchedHandle, TaskFromFriend, PinnedTask, NewNeighbor};
233 use sleeper_list::SleeperList;
234 use stack::StackPool;
235 use task::GreenTask;
236
237 mod macros;
238 mod simple;
239 mod message_queue;
240
241 pub mod basic;
242 pub mod context;
243 pub mod coroutine;
244 pub mod sched;
245 pub mod sleeper_list;
246 pub mod stack;
247 pub mod task;
248
249 /// A helper macro for booting a program with libgreen
250 ///
251 /// # Example
252 ///
253 /// ```
254 /// #![feature(phase)]
255 /// #[phase(plugin)] extern crate green;
256 ///
257 /// green_start!(main)
258 ///
259 /// fn main() {
260 ///     // running with libgreen
261 /// }
262 /// ```
263 #[macro_export]
264 macro_rules! green_start( ($f:ident) => (
265     mod __start {
266         extern crate green;
267         extern crate rustuv;
268
269         #[start]
270         fn start(argc: int, argv: *const *const u8) -> int {
271             green::start(argc, argv, rustuv::event_loop, super::$f)
272         }
273     }
274 ) )
275
276 /// Set up a default runtime configuration, given compiler-supplied arguments.
277 ///
278 /// This function will block until the entire pool of M:N schedulers have
279 /// exited. This function also requires a local task to be available.
280 ///
281 /// # Arguments
282 ///
283 /// * `argc` & `argv` - The argument vector. On Unix this information is used
284 ///   by os::args.
285 /// * `main` - The initial procedure to run inside of the M:N scheduling pool.
286 ///            Once this procedure exits, the scheduling pool will begin to shut
287 ///            down. The entire pool (and this function) will only return once
288 ///            all child tasks have finished executing.
289 ///
290 /// # Return value
291 ///
292 /// The return value is used as the process return code. 0 on success, 101 on
293 /// error.
294 pub fn start(argc: int, argv: *const *const u8,
295              event_loop_factory: fn() -> Box<rtio::EventLoop + Send>,
296              main: proc():Send) -> int {
297     rt::init(argc, argv);
298     let mut main = Some(main);
299     let mut ret = None;
300     simple::task().run(|| {
301         ret = Some(run(event_loop_factory, main.take_unwrap()));
302     });
303     // unsafe is ok b/c we're sure that the runtime is gone
304     unsafe { rt::cleanup() }
305     ret.unwrap()
306 }
307
308 /// Execute the main function in a pool of M:N schedulers.
309 ///
310 /// Configures the runtime according to the environment, by default using a task
311 /// scheduler with the same number of threads as cores.  Returns a process exit
312 /// code.
313 ///
314 /// This function will not return until all schedulers in the associated pool
315 /// have returned.
316 pub fn run(event_loop_factory: fn() -> Box<rtio::EventLoop + Send>,
317            main: proc():Send) -> int {
318     // Create a scheduler pool and spawn the main task into this pool. We will
319     // get notified over a channel when the main task exits.
320     let mut cfg = PoolConfig::new();
321     cfg.event_loop_factory = event_loop_factory;
322     let mut pool = SchedPool::new(cfg);
323     let (tx, rx) = channel();
324     let mut opts = TaskOpts::new();
325     opts.on_exit = Some(proc(r) tx.send(r));
326     opts.name = Some("<main>".into_maybe_owned());
327     pool.spawn(opts, main);
328
329     // Wait for the main task to return, and set the process error code
330     // appropriately.
331     if rx.recv().is_err() {
332         os::set_exit_status(rt::DEFAULT_ERROR_CODE);
333     }
334
335     // Now that we're sure all tasks are dead, shut down the pool of schedulers,
336     // waiting for them all to return.
337     pool.shutdown();
338     os::get_exit_status()
339 }
340
341 /// Configuration of how an M:N pool of schedulers is spawned.
342 pub struct PoolConfig {
343     /// The number of schedulers (OS threads) to spawn into this M:N pool.
344     pub threads: uint,
345     /// A factory function used to create new event loops. If this is not
346     /// specified then the default event loop factory is used.
347     pub event_loop_factory: fn() -> Box<rtio::EventLoop + Send>,
348 }
349
350 impl PoolConfig {
351     /// Returns the default configuration, as determined the environment
352     /// variables of this process.
353     pub fn new() -> PoolConfig {
354         PoolConfig {
355             threads: rt::default_sched_threads(),
356             event_loop_factory: basic::event_loop,
357         }
358     }
359 }
360
361 /// A structure representing a handle to a pool of schedulers. This handle is
362 /// used to keep the pool alive and also reap the status from the pool.
363 pub struct SchedPool {
364     id: uint,
365     threads: Vec<Thread<()>>,
366     handles: Vec<SchedHandle>,
367     stealers: Vec<deque::Stealer<Box<task::GreenTask>>>,
368     next_friend: uint,
369     stack_pool: StackPool,
370     deque_pool: deque::BufferPool<Box<task::GreenTask>>,
371     sleepers: SleeperList,
372     factory: fn() -> Box<rtio::EventLoop + Send>,
373     task_state: TaskState,
374     tasks_done: Receiver<()>,
375 }
376
377 /// This is an internal state shared among a pool of schedulers. This is used to
378 /// keep track of how many tasks are currently running in the pool and then
379 /// sending on a channel once the entire pool has been drained of all tasks.
380 #[deriving(Clone)]
381 struct TaskState {
382     cnt: Arc<AtomicUint>,
383     done: Sender<()>,
384 }
385
386 impl SchedPool {
387     /// Execute the main function in a pool of M:N schedulers.
388     ///
389     /// This will configure the pool according to the `config` parameter, and
390     /// initially run `main` inside the pool of schedulers.
391     pub fn new(config: PoolConfig) -> SchedPool {
392         static mut POOL_ID: AtomicUint = INIT_ATOMIC_UINT;
393
394         let PoolConfig {
395             threads: nscheds,
396             event_loop_factory: factory
397         } = config;
398         assert!(nscheds > 0);
399
400         // The pool of schedulers that will be returned from this function
401         let (p, state) = TaskState::new();
402         let mut pool = SchedPool {
403             threads: vec![],
404             handles: vec![],
405             stealers: vec![],
406             id: unsafe { POOL_ID.fetch_add(1, SeqCst) },
407             sleepers: SleeperList::new(),
408             stack_pool: StackPool::new(),
409             deque_pool: deque::BufferPool::new(),
410             next_friend: 0,
411             factory: factory,
412             task_state: state,
413             tasks_done: p,
414         };
415
416         // Create a work queue for each scheduler, ntimes. Create an extra
417         // for the main thread if that flag is set. We won't steal from it.
418         let mut workers = Vec::with_capacity(nscheds);
419         let mut stealers = Vec::with_capacity(nscheds);
420
421         for _ in range(0, nscheds) {
422             let (w, s) = pool.deque_pool.deque();
423             workers.push(w);
424             stealers.push(s);
425         }
426         pool.stealers = stealers;
427
428         // Now that we've got all our work queues, create one scheduler per
429         // queue, spawn the scheduler into a thread, and be sure to keep a
430         // handle to the scheduler and the thread to keep them alive.
431         for worker in workers.move_iter() {
432             rtdebug!("inserting a regular scheduler");
433
434             let mut sched = box Scheduler::new(pool.id,
435                                             (pool.factory)(),
436                                             worker,
437                                             pool.stealers.clone(),
438                                             pool.sleepers.clone(),
439                                             pool.task_state.clone());
440             pool.handles.push(sched.make_handle());
441             pool.threads.push(Thread::start(proc() { sched.bootstrap(); }));
442         }
443
444         return pool;
445     }
446
447     /// Creates a new task configured to run inside of this pool of schedulers.
448     /// This is useful to create a task which can then be sent to a specific
449     /// scheduler created by `spawn_sched` (and possibly pin it to that
450     /// scheduler).
451     #[deprecated = "use the green and green_pinned methods of GreenTaskBuilder instead"]
452     pub fn task(&mut self, opts: TaskOpts, f: proc():Send) -> Box<GreenTask> {
453         GreenTask::configure(&mut self.stack_pool, opts, f)
454     }
455
456     /// Spawns a new task into this pool of schedulers, using the specified
457     /// options to configure the new task which is spawned.
458     ///
459     /// New tasks are spawned in a round-robin fashion to the schedulers in this
460     /// pool, but tasks can certainly migrate among schedulers once they're in
461     /// the pool.
462     #[deprecated = "use the green and green_pinned methods of GreenTaskBuilder instead"]
463     pub fn spawn(&mut self, opts: TaskOpts, f: proc():Send) {
464         let task = self.task(opts, f);
465
466         // Figure out someone to send this task to
467         let idx = self.next_friend;
468         self.next_friend += 1;
469         if self.next_friend >= self.handles.len() {
470             self.next_friend = 0;
471         }
472
473         // Jettison the task away!
474         self.handles.get_mut(idx).send(TaskFromFriend(task));
475     }
476
477     /// Spawns a new scheduler into this M:N pool. A handle is returned to the
478     /// scheduler for use. The scheduler will not exit as long as this handle is
479     /// active.
480     ///
481     /// The scheduler spawned will participate in work stealing with all of the
482     /// other schedulers currently in the scheduler pool.
483     pub fn spawn_sched(&mut self) -> SchedHandle {
484         let (worker, stealer) = self.deque_pool.deque();
485         self.stealers.push(stealer.clone());
486
487         // Tell all existing schedulers about this new scheduler so they can all
488         // steal work from it
489         for handle in self.handles.mut_iter() {
490             handle.send(NewNeighbor(stealer.clone()));
491         }
492
493         // Create the new scheduler, using the same sleeper list as all the
494         // other schedulers as well as having a stealer handle to all other
495         // schedulers.
496         let mut sched = box Scheduler::new(self.id,
497                                         (self.factory)(),
498                                         worker,
499                                         self.stealers.clone(),
500                                         self.sleepers.clone(),
501                                         self.task_state.clone());
502         let ret = sched.make_handle();
503         self.handles.push(sched.make_handle());
504         self.threads.push(Thread::start(proc() { sched.bootstrap() }));
505
506         return ret;
507     }
508
509     /// Consumes the pool of schedulers, waiting for all tasks to exit and all
510     /// schedulers to shut down.
511     ///
512     /// This function is required to be called in order to drop a pool of
513     /// schedulers, it is considered an error to drop a pool without calling
514     /// this method.
515     ///
516     /// This only waits for all tasks in *this pool* of schedulers to exit, any
517     /// native tasks or extern pools will not be waited on
518     pub fn shutdown(mut self) {
519         self.stealers = vec![];
520
521         // Wait for everyone to exit. We may have reached a 0-task count
522         // multiple times in the past, meaning there could be several buffered
523         // messages on the `tasks_done` port. We're guaranteed that after *some*
524         // message the current task count will be 0, so we just receive in a
525         // loop until everything is totally dead.
526         while self.task_state.active() {
527             self.tasks_done.recv();
528         }
529
530         // Now that everyone's gone, tell everything to shut down.
531         for mut handle in replace(&mut self.handles, vec![]).move_iter() {
532             handle.send(Shutdown);
533         }
534         for thread in replace(&mut self.threads, vec![]).move_iter() {
535             thread.join();
536         }
537     }
538 }
539
540 impl TaskState {
541     fn new() -> (Receiver<()>, TaskState) {
542         let (tx, rx) = channel();
543         (rx, TaskState {
544             cnt: Arc::new(AtomicUint::new(0)),
545             done: tx,
546         })
547     }
548
549     fn increment(&mut self) {
550         self.cnt.fetch_add(1, SeqCst);
551     }
552
553     fn active(&self) -> bool {
554         self.cnt.load(SeqCst) != 0
555     }
556
557     fn decrement(&mut self) {
558         let prev = self.cnt.fetch_sub(1, SeqCst);
559         if prev == 1 {
560             self.done.send(());
561         }
562     }
563 }
564
565 impl Drop for SchedPool {
566     fn drop(&mut self) {
567         if self.threads.len() > 0 {
568             fail!("dropping a M:N scheduler pool that wasn't shut down");
569         }
570     }
571 }
572
573 /// A spawner for green tasks
574 pub struct GreenSpawner<'a>{
575     pool: &'a mut SchedPool,
576     handle: Option<&'a mut SchedHandle>
577 }
578
579 impl<'a> Spawner for GreenSpawner<'a> {
580     #[inline]
581     fn spawn(self, opts: TaskOpts, f: proc():Send) {
582         let GreenSpawner { pool, handle } = self;
583         match handle {
584             None    => pool.spawn(opts, f),
585             Some(h) => h.send(PinnedTask(pool.task(opts, f)))
586         }
587     }
588 }
589
590 /// An extension trait adding `green` configuration methods to `TaskBuilder`.
591 pub trait GreenTaskBuilder {
592     fn green<'a>(self, &'a mut SchedPool) -> TaskBuilder<GreenSpawner<'a>>;
593     fn green_pinned<'a>(self, &'a mut SchedPool, &'a mut SchedHandle)
594                         -> TaskBuilder<GreenSpawner<'a>>;
595 }
596
597 impl<S: Spawner> GreenTaskBuilder for TaskBuilder<S> {
598     fn green<'a>(self, pool: &'a mut SchedPool) -> TaskBuilder<GreenSpawner<'a>> {
599         self.spawner(GreenSpawner {pool: pool, handle: None})
600     }
601
602     fn green_pinned<'a>(self, pool: &'a mut SchedPool, handle: &'a mut SchedHandle)
603                         -> TaskBuilder<GreenSpawner<'a>> {
604         self.spawner(GreenSpawner {pool: pool, handle: Some(handle)})
605     }
606 }
607
608 #[cfg(test)]
609 mod test {
610     use std::task::TaskBuilder;
611     use super::{SchedPool, PoolConfig, GreenTaskBuilder};
612
613     #[test]
614     fn test_green_builder() {
615         let mut pool = SchedPool::new(PoolConfig::new());
616         let res = TaskBuilder::new().green(&mut pool).try(proc() {
617             "Success!".to_string()
618         });
619         assert_eq!(res.ok().unwrap(), "Success!".to_string());
620         pool.shutdown();
621     }
622 }