#channel #thread #sync #message-passing

swctx

One-shot channel with some special semantics

6 releases

0.3.0 Sep 9, 2024
0.2.2 Jan 14, 2024
0.2.1 Aug 14, 2023
0.1.1 Aug 8, 2023
0.1.0 Jul 30, 2023

#557 in Concurrency


Used in 8 crates (6 directly)

0BSD license

15KB
256 lines

swctx

Set/Wait Context (swctx) is a one-shot channel-like construct with some special semantics.


lib.rs:

swctx is similar to a cross-thread/task one-shot channel, with the added ability to store a generic "current state" of the channel prior to passing a value over the channel.

use std::thread;
use swctx::mkpair;

let (sctx, wctx) = mkpair::<&str, &str, &str>();
let jh = thread::spawn(move || {
  sctx.set_state("in thread");
  sctx.set("hello");
});
jh.join().unwrap();

assert_eq!(wctx.wait().unwrap(), "hello");

In a typical use-case an application or library calls [mkpair()] to create a pair of linked SetCtx and WaitCtx object. The SetCtx object is transferred to a remote thread/task, and the WaitCtx is used wait for an object to arrive [from the thread/task the SetCtx is sent to].

Once the thread/task has data to send back to the WaitCtx it calls [SetCtx::set()] to send the data.

The SetCtx has an internal state, settable using [SetCtx::set_state()] that will be reported back to the WaitCtx, which will return Error::Aborted, if the SetCtx is dropped prematurely.

The SetCtx can also signal a failure by calling [SetCtx::fail()] and pass along an application-specific error code. This will cause the WaitCtx to unblock and return Error::App.

Dependencies

~0.4–5MB
~11K SLoC