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
use crate::park::Unpark;
use crate::runtime::thread_pool::slice;
use crate::runtime::Unparker;
use crate::task::{self, Schedule, ScheduleSendOnly, Task};

use std::ptr;

/// Per-worker data accessible from any thread.
///
/// Accessed by:
///
/// - other workers
/// - tasks
///
pub(crate) struct Shared {
    /// Thread unparker
    unpark: Unparker,

    /// Tasks pending drop. Any worker pushes tasks, only the "owning" worker
    /// pops.
    pub(super) pending_drop: task::TransferStack<Self>,

    /// Untracked pointer to the pool.
    ///
    /// The slice::Set itself is tracked by an `Arc`, but this pointer is not
    /// included in the ref count.
    slices: *const slice::Set,
}

unsafe impl Send for Shared {}
unsafe impl Sync for Shared {}

impl Shared {
    pub(super) fn new(unpark: Unparker) -> Shared {
        Shared {
            unpark,
            pending_drop: task::TransferStack::new(),
            slices: ptr::null(),
        }
    }

    pub(crate) fn schedule(&self, task: Task<Self>) {
        self.slices().schedule(task);
    }

    pub(super) fn unpark(&self) {
        self.unpark.unpark();
    }

    fn slices(&self) -> &slice::Set {
        unsafe { &*self.slices }
    }

    pub(super) fn set_slices_ptr(&mut self, slices: *const slice::Set) {
        self.slices = slices;
    }
}

impl Schedule for Shared {
    fn bind(&self, task: &Task<Self>) {
        // Get access to the Owned component. This function can only be called
        // when on the worker.
        unsafe {
            let index = self.slices().index_of(self);
            let owned = &mut *self.slices().owned()[index].get();

            owned.bind_task(task);
        }
    }

    fn release(&self, task: Task<Self>) {
        // This stores the task with the owning worker. The worker is not
        // notified. Instead, the worker will clean up the tasks "eventually".
        //
        self.pending_drop.push(task);
    }

    fn release_local(&self, task: &Task<Self>) {
        // Get access to the Owned component. This function can only be called
        // when on the worker.
        unsafe {
            let index = self.slices().index_of(self);
            let owned = &mut *self.slices().owned()[index].get();

            owned.release_task(task);
        }
    }

    fn schedule(&self, task: Task<Self>) {
        Self::schedule(self, task);
    }
}

impl ScheduleSendOnly for Shared {}