Process

Struct Process 

Source
pub struct Process { /* private fields */ }
Expand description

A light weight task that can send and receive messages.

Implementations§

Source§

impl Process

Source

pub fn alias(reply: bool) -> Reference

Creates a process alias. If reply is true the alias deactivates when the first message is received.

Otherwise, you need to call unalias(reference) to deactivate the alias.

Source

pub fn unalias(alias: Reference) -> bool

Explicitly deactivates a process alias.

Returns true if the alias was currently-active for the current process, or false otherwise.

Source

pub fn current() -> Pid

Returns the current Pid.

Examples found in repository?
examples/supervisor.rs (line 75)
74    async fn init(&mut self) -> Result<(), ExitReason> {
75        let server = Process::current();
76
77        Process::spawn(async move {
78            // Ask for a formatted string.
79            let hello_world = MyServer::hello(server, "hello")
80                .await
81                .expect("Failed to call server!");
82
83            tracing::info!("Got: {:?}", hello_world);
84
85            // Wait before crashing.
86            Process::sleep(Duration::from_secs(1)).await;
87
88            // Crash the process so the supervisor restarts it.
89            MyServer::cast(server, MyMessage::Crash);
90        });
91
92        Ok(())
93    }
Source

pub fn whereis<S: AsRef<str>>(name: S) -> Option<Pid>

Returns the Pid registered under name or None if the name is not registered.

Source

pub fn send<D: Into<Dests>, M: Receivable>(dests: D, message: M)

Sends a message to dests.

§Example:

This method allows sending to multiple targets with certain trade offs:

let pid1 = Process::spawn(async { /* */ });
let pid2 = Process::spawn(async { /* */ });

// faster when all processes are local.
for pid in &[pid1, pid2] {
    Process::send(pid, "hello world!");
}

// faster when processes are mostly remote.
Process::send(&[pid1, pid2], "hello world!");
Source

pub fn send_after<D: Into<Dests>, M: Receivable>( dest: D, message: M, duration: Duration, ) -> Reference

Sends a message to dests after the given duration.

See Process::send for performance trade-offs.

§Example:

Sends a message after 5 seconds to pid:

Process::send_after(pid, "hello world!", Duration::from_secs(5));
Source

pub fn cancel_timer(timer: Reference)

Cancels a timer created by send_after.

Source

pub fn read_timer(timer: Reference) -> Option<Duration>

Reads a timer created by send_after.

It returns the time remaining until the timer expires.

Source

pub fn receiver() -> ProcessReceiver<()>

Creates a receiver with advanced filtering options from the current processes mailbox.

Source

pub async fn receive<T: Receivable>() -> Message<T>

Creates a receiver for a single message that matches the given type from the current processes mailbox.

This will panic if a message is received that doesn’t match the given type.

Source

pub fn spawn<T>(function: T) -> Pid
where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static,

Spawns the given function as a process and returns it’s Pid.

Examples found in repository?
examples/supervisor.rs (lines 77-90)
74    async fn init(&mut self) -> Result<(), ExitReason> {
75        let server = Process::current();
76
77        Process::spawn(async move {
78            // Ask for a formatted string.
79            let hello_world = MyServer::hello(server, "hello")
80                .await
81                .expect("Failed to call server!");
82
83            tracing::info!("Got: {:?}", hello_world);
84
85            // Wait before crashing.
86            Process::sleep(Duration::from_secs(1)).await;
87
88            // Crash the process so the supervisor restarts it.
89            MyServer::cast(server, MyMessage::Crash);
90        });
91
92        Ok(())
93    }
More examples
Hide additional examples
examples/registry.rs (line 73)
58    async fn start(&self) -> Result<Pid, ExitReason> {
59        // Spawn a registry that will take care of registering 'MySpace'.
60        let children = [
61            Registry::new("space-registry")
62                .with_start(|key| {
63                    let RegistryKey::String(id) = key else {
64                        panic!()
65                    };
66
67                    MySpace::new(id).start_link(GenServerOptions::new())
68                })
69                .with_shutdown(Shutdown::Infinity)
70                .child_spec(RegistryOptions::new())
71                .id("space-registry"),
72            ChildSpec::new("test-registry")
73                .start(move || async { Ok(Process::spawn(test_registry())) }),
74        ];
75
76        // Restart only the terminated child.
77        Supervisor::with_children(children)
78            .strategy(SupervisionStrategy::OneForOne)
79            .start_link(SupervisorOptions::new())
80            .await
81    }

Spawns the given function as a process, creates a link between the calling process, and returns the new Pid.

Source

pub fn spawn_monitor<T>(function: T) -> (Pid, Reference)
where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static,

Spawns the given function as a process, creates a monitor for the calling process, and returns the new Pid.

Source

pub fn alive(pid: Pid) -> bool

Returns true if the given Pid is alive on the local node.

Source

pub async fn sleep(duration: Duration)

Sleeps the current process for the given duration.

Examples found in repository?
examples/registry.rs (line 110)
107    async fn terminate(&mut self, _reason: ExitReason) {
108        tracing::info!("Shutting down MySpace! {:?}", self.id);
109
110        Process::sleep(Duration::from_secs(5)).await;
111    }
More examples
Hide additional examples
examples/supervisor.rs (line 86)
74    async fn init(&mut self) -> Result<(), ExitReason> {
75        let server = Process::current();
76
77        Process::spawn(async move {
78            // Ask for a formatted string.
79            let hello_world = MyServer::hello(server, "hello")
80                .await
81                .expect("Failed to call server!");
82
83            tracing::info!("Got: {:?}", hello_world);
84
85            // Wait before crashing.
86            Process::sleep(Duration::from_secs(1)).await;
87
88            // Crash the process so the supervisor restarts it.
89            MyServer::cast(server, MyMessage::Crash);
90        });
91
92        Ok(())
93    }
Source

pub async fn timeout<F>( duration: Duration, future: F, ) -> Result<<F as Future>::Output, Timeout>
where F: Future,

Waits for the given future to complete until the given duration is up.

Source

pub fn register<S: Into<String>>(pid: Pid, name: S) -> Result<(), ArgumentError>

Registers the given Pid under name if the process is local, active, and the name is not already registered.

Source

pub fn unregister<S: AsRef<str>>(name: S)

Removes the registered name, associated with a Pid.

Source

pub fn registered() -> Vec<String>

Returns a Vec of registered process names.

Source

pub fn list() -> Vec<Pid>

Returns a Vec of Pid’s on the local node.

Creates a bi-directional link between the current process and the given process.

Removes the link between the calling process and the given process.

Source

pub fn monitor<T: Into<Dest>>(process: T) -> Reference

Starts monitoring the given process from the calling process. If the process is already dead a message is sent immediately.

Source

pub fn monitor_alias<T: Into<Dest>>(process: T, reply: bool) -> Reference

Starts monitoring the given process from the calling process. If the process is already dead a message is sent immediately.

Creates an alias for the calling process that’s tied to the process monitor.

The alias will be deactivated if:

  • The monitor sends a down message.
  • The user explicitly calls unalias. (The monitor will remain active)
  • reply is true and a message is sent over the alias.
Source

pub fn demonitor(monitor: Reference)

Demonitors the monitor identified by the given reference.

If a monitor message was sent to the process already but was not received, it will be discarded automatically.

Source

pub fn flags() -> ProcessFlags

Returns the current process flags.

Source

pub fn set_flags(flags: ProcessFlags)

Sets one or more process flags.

Examples found in repository?
examples/registry.rs (line 100)
99    async fn init(&mut self) -> Result<(), ExitReason> {
100        Process::set_flags(ProcessFlags::TRAP_EXIT);
101
102        tracing::info!("Init MySpace for {:?}", self.id);
103
104        Ok(())
105    }
Source

pub fn exit<E: Into<ExitReason>>(pid: Pid, exit_reason: E)

Sends an exit signal with the given reason to Pid.

Source

pub fn info(pid: Pid) -> Option<ProcessInfo>

Fetches debug information for a given local process.

Trait Implementations§

Source§

impl Drop for Process

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl !Freeze for Process

§

impl !RefUnwindSafe for Process

§

impl Send for Process

§

impl !Sync for Process

§

impl Unpin for Process

§

impl !UnwindSafe for Process

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more