{"id":376,"date":"2024-07-13T20:32:24","date_gmt":"2024-07-13T12:32:24","guid":{"rendered":"https:\/\/cococat.top\/?p=376"},"modified":"2024-07-13T20:32:24","modified_gmt":"2024-07-13T12:32:24","slug":"rust-note-6-notify-vs-oneshot","status":"publish","type":"post","link":"https:\/\/cococat.top\/index.php\/2024\/07\/13\/rust-note-6-notify-vs-oneshot\/","title":{"rendered":"rust \u7b14\u8bb0 6\uff1aNotify vs oneshot::channel"},"content":{"rendered":"<h2>1. \u5171\u6027\u4e0e\u533a\u522b<\/h2>\n<p>\u5199\u5f02\u6b65 rust \u65f6\uff0c\u6211\u4eec\u7ecf\u5e38\u9700\u8981\u4e00\u79cd\u4e00\u6b21\u6027\u7684\u901a\u77e5\u624b\u6bb5\uff0c\u7528\u4e8e\u5b9e\u73b0\u7ebf\u7a0b\u540c\u6b65\u3002tokio \u63d0\u4f9b\u4e86\u4e24\u79cd\u6ee1\u8db3\u4e0a\u8ff0\u9700\u6c42\u7684\u540c\u6b65\u5de5\u5177\uff1a<code>tokio::sync::oneshot::channel<\/code> \u548c <code>tokio::sync::Notify<\/code>\u3002<\/p>\n<p>\u4e8c\u8005\u4e3b\u8981\u6709\u4ee5\u4e0b\u51e0\u70b9\u5dee\u8ddd\uff1a<\/p>\n<h3>1.1. \u5355\u7aef\u4e0e\u53cc\u7aef\u8bbe\u8ba1<\/h3>\n<p>\u5bf9\u4e8e <code>oneshot::channel<\/code> \uff0c\u81ea\u7136\u5730\u5206\u4e3a\u53d1\u9001\u7aef <code>Sender<\/code> \u548c\u63a5\u6536\u7aef <code>Receiver<\/code>\uff0c\u4e8c\u8005\u804c\u8d23\u5206\u660e\u3002<\/p>\n<p>\u7136\u800c\uff0c\u5bf9\u4e8e <code>Notify<\/code> \uff0c\u4efb\u610f\u4e00\u4e2a\u88ab clone \u7684\u5b9e\u4f8b\uff08\u5b9e\u9645\u4e0a\uff0c<code>Notify<\/code> \u672c\u8eab\u4e0d\u5b9e\u73b0 <code>Clone<\/code>, \u6240\u4ee5\u4e00\u822c\u662f\u7528 <code>Arc<\/code> \u5305\u8d77\u6765\uff09\uff0c\u65e2\u80fd\u62ff\u6765\u5f53\u505a\u53d1\u9001\u7aef\uff08notifier\uff09\uff0c\u4e5f\u80fd\u62ff\u6765\u5f53\u63a5\u6536\u7aef\uff08waiter\uff09\u3002<\/p>\n<pre><code class=\"language-rust\">let a = Arc::new(Notify::new());\nlet b = a.clone();\n\ntokio::spawn(async move {\n    println!(&quot;a is waiting for notification...&quot;);\n    a.notified().await;\n    println!(&quot;a is notified!&quot;);\n    println!(&quot;a is now notifying b...&quot;);\n    a.notify_one();\n});\n\nprintln!(&quot;b is now notifying a...&quot;);\nb.notify_one();\nprintln!(&quot;b is waiting for notification...&quot;);\nb.notified().await;\nprintln!(&quot;b is notified!&quot;);<\/code><\/pre>\n<h3>1.2. \u901a\u77e5\u65b9\u4e0e\u7b49\u5f85\u65b9\u7684\u6570\u91cf<\/h3>\n<p>\u5bf9\u4e8e <code>oneshot::channel<\/code>\uff0c\u65e0\u8bba\u662f <code>Sender<\/code> \u8fd8\u662f <code>Receiver<\/code> \u90fd\u53ea\u80fd\u6709\u4e00\u4e2a\uff0c clone \u662f\u4e0d\u88ab\u5141\u8bb8\u7684\u3002<\/p>\n<p>\u76f8\u53cd\uff0c<code>Notify<\/code> \u5728 <code>Arc<\/code> \u4ee5\u540e\u53ef\u4ee5\u4efb\u610f clone\uff0c\u5373\u901a\u77e5\u65b9\u548c\u7b49\u5f85\u65b9\u90fd\u53ef\u4ee5\u6709\u4efb\u610f\u4e2a\u6570\u3002\u6b63\u56e0\u5982\u6b64\uff0c<code>Notify<\/code> \u63d0\u4f9b\u4e86\u4e24\u79cd\u63a5\u53e3\uff0c\u6709\u53ea\u5524\u9192\u4e00\u4e2a\u7b49\u5f85\u65b9\u7684 <code>notify_one<\/code> \u548c\u5524\u9192\u6240\u6709\u7b49\u5f85\u65b9\u7684 <code>notify_waiters<\/code>\u3002<\/p>\n<h3>1.3. \u643a\u5e26\u6570\u636e<\/h3>\n<p>\u6700\u540e\uff0c\u663e\u800c\u6613\u89c1\u5730\uff0c<code>channel<\/code> \u662f\u53ef\u4ee5\u643a\u5e26\u6570\u636e\u7684\uff0c\u4f46\u662f <code>Notify<\/code> \u53ea\u80fd\u7528\u6765\u8fdb\u884c\u901a\u77e5\uff0c\u5e76\u4e0d\u80fd\u643a\u5e26\u4efb\u4f55\u6570\u636e\u3002<\/p>\n<h2>2. \u7b80\u5316\u7248\u7684\u5b9e\u73b0\u539f\u7406<\/h2>\n<h3>2.1. <code>Notify<\/code><\/h3>\n<p><code>Notify<\/code> \u7684\u5b9a\u4e49\u5982\u4e0b\uff1a<\/p>\n<pre><code class=\"language-rust\">pub struct Notify {\n    state: AtomicUsize,\n    waiters: Mutex&lt;WaitList&gt;,\n}<\/code><\/pre>\n<p>\u53ef\u89c1\u57fa\u672c\u8bbe\u8ba1\u601d\u60f3\u662f\u7528\u4e00\u4e2a atomic \u7684 state \u6765\u8bb0\u5f55\u72b6\u6001\uff0c\u7136\u540e\u5728\u5176\u57fa\u7840\u4e0a\u505a CAS \u6765\u5b8c\u6210\u6240\u6709\u7684\u72b6\u6001\u8f6c\u79fb\u3002<\/p>\n<p>\u5f53\u9700\u8981 Pending \u6765\u7b49\u5f85\u901a\u77e5\u65f6\uff0c\u8c03\u7528\u65b9\u5c06\u81ea\u5df1\u7684 <code>waker<\/code> \u653e\u5165 <code>waiters<\/code> \u4e2d\u4fdd\u5b58\u3002\u901a\u77e5\u65b9\u5219\u4ece\u4e2d\u53d6\u51fa <code>waker<\/code> \u5e76\u8c03\u7528 <code>wake()<\/code> \u8fdb\u884c\u5524\u9192\u3002\u8fd9\u6837\u4e00\u6765\uff0c\u786e\u5b9e\u53ea\u9700\u8981\u4e00\u4e2a\u5168\u5c40\u5b9e\u4f8b\uff0c\u5404\u65b9\u5747\u4f7f\u7528 <code>Arc<\/code> \u8bbf\u95ee\u5373\u53ef\u3002<\/p>\n<h3>2.2. <code>oneshot::channel<\/code><\/h3>\n<p><code>oneshot::channel<\/code> \u7684\u771f\u5b9e\u5b9e\u73b0\u7a0d\u5fae\u590d\u6742\u4e00\u70b9\u70b9\uff0c\u4e3a\u4e86\u7b80\u660e\u627c\u8981\u5730\u8bf4\u660e\u539f\u7406\uff0c\u4e0b\u9762\u7684\u4ee3\u7801\u53bb\u6389\u4e86\u4e00\u4e9b\u5b57\u6bb5\uff1a<\/p>\n<pre><code class=\"language-rust\">pub struct Sender&lt;T&gt; {\n    inner: Option&lt;Arc&lt;Inner&lt;T&gt;&gt;&gt;,\n}\n\npub struct Receiver&lt;T&gt; {\n    inner: Option&lt;Arc&lt;Inner&lt;T&gt;&gt;&gt;,\n}\n\nstruct Inner&lt;T&gt; {\n    state: AtomicUsize,\n    value: UnsafeCell&lt;Option&lt;T&gt;&gt;,\n    tx_task: Task,\n    rx_task: Task,\n}\n\nstruct Task(UnsafeCell&lt;MaybeUninit&lt;Waker&gt;&gt;);<\/code><\/pre>\n<p>\u53ef\u4ee5\u770b\u5230\u4e00\u4e9b\u5171\u6027\u7684\u4e1c\u897f\uff0c\u4f8b\u5982\u4e5f\u9700\u8981\u57fa\u4e8e\u4e00\u4e2a atomic \u6765\u505a CAS\u3002\u4e0d\u8fc7\u7531\u4e8e\u662f\u53cc\u7aef\u8bbe\u8ba1\uff0c\u56e0\u6b64\u9700\u8981\u4f7f\u7528 <code>Arc<\/code> \u6765\u5171\u7528 <code>Inner<\/code>\uff0c\u5e76\u4e14 <code>Inner<\/code> \u4e2d\u9700\u8981\u4fdd\u5b58 <code>Receiver<\/code> \u548c <code>Sender<\/code> \u5404\u81ea\u7684 waker\u3002<\/p>\n<h3>2.3. \u7406\u8bba\u4e0a\u7684\u6027\u80fd\u5dee\u8ddd<\/h3>\n<p>\u6709\u4e00\u4e2a\u95ee\u9898\u9700\u8981\u6ce8\u610f\uff1a<code>Notify<\/code> \u652f\u6301\u591a\u4e2a\u7b49\u5f85\u5524\u9192\u65b9\uff0c\u5176\u4ee3\u7801\u5b9e\u73b0\u4f7f\u7528\u4e86\u94fe\u8868\u6765\u5b58\u653e\u8fd9\u4e9b\u7b49\u5f85\u65b9\u7684 waker \uff0c\u56e0\u6b64\u5728\u5f39\u51fa waker \u8fdb\u884c\u5524\u9192\u65f6\uff0c\u662f\u65e0\u6cd5\u907f\u514d\u8981\u52a0\u9501\u7684\u3002\u6211\u4eec\u6765\u770b\u4e00\u4e0b <code>notify_with_strategy<\/code> \u65b9\u6cd5\uff0c\u8fd9\u662f\u5728\u8c03\u7528 <code>Notify::notify_one<\/code> \u65f6\u5b9e\u9645\u4e0a\u8c03\u7528\u7684\u5e95\u5c42\u51fd\u6570\u3002<\/p>\n<pre><code class=\"language-rust\">fn notify_with_strategy(&amp;self, strategy: NotifyOneStrategy) {\n    \/\/ Load the current state\n    let mut curr = self.state.load(SeqCst);\n\n    \/\/ If the state is `EMPTY`, transition to `NOTIFIED` and return.\n    while let EMPTY | NOTIFIED = get_state(curr) {\n        \/\/ The compare-exchange from `NOTIFIED` -&gt; `NOTIFIED` is intended. A\n        \/\/ happens-before synchronization must happen between this atomic\n        \/\/ operation and a task calling `notified().await`.\n        let new = set_state(curr, NOTIFIED);\n        let res = self.state.compare_exchange(curr, new, SeqCst, SeqCst);\n\n        match res {\n            \/\/ No waiters, no further work to do\n            Ok(_) =&gt; return,\n            Err(actual) =&gt; {\n                curr = actual;\n            }\n        }\n    }\n\n    \/\/ There are waiters, the lock must be acquired to notify.\n    let mut waiters = self.waiters.lock();\n\n    \/\/ The state must be reloaded while the lock is held. The state may only\n    \/\/ transition out of WAITING while the lock is held.\n    curr = self.state.load(SeqCst);\n\n    if let Some(waker) = notify_locked(&amp;mut waiters, &amp;self.state, curr, strategy) {\n        drop(waiters);\n        waker.wake();\n    }\n}<\/code><\/pre>\n<p>\u53ef\u89c1\u5728\u5f39\u51fa waker \u65f6\uff0c\u4f7f\u7528\u4e86 <code>self.waiters.lock()<\/code> \u3002<\/p>\n<p>\u800c\u5bf9\u4e8e oneshot \uff0c\u5c3d\u7ba1\u903b\u8f91\u8f83\u4e3a\u590d\u6742\uff0c\u4f46\u662f\u5176\u5e95\u5c42\u5b9e\u73b0\u662f\u5b8c\u5168\u65e0\u9501\u7684\uff0c\u56e0\u6b64\u4e8c\u8005\u6027\u80fd\u5b70\u9ad8\u5b70\u4f4e\u8fd8\u4e0d\u597d\u5b9a\u8bba\u3002<\/p>\n<h2>3. \u6027\u80fd\u6d4b\u8bd5<\/h2>\n<p>\u5728\u9762\u5411\u7f51\u7edc\u3001\u6570\u636e\u5e93\u7b49\u573a\u666f\u7684\u5e94\u7528\u4e2d\uff0c\u8fde\u63a5\u6c60\u662f\u5e38\u89c1\u7684\u6027\u80fd\u4f18\u5316\u65b9\u6848\u3002\u8bbe\u8ba1\u8fde\u63a5\u6c60\u65f6\uff0c\u4e00\u822c\u90fd\u9700\u8981\u611f\u77e5\u8fde\u63a5\u7684\u5b58\u6d3b\u60c5\u51b5\uff0c\u4e00\u65e6\u53d1\u73b0\u8fde\u63a5\u88ab\u5bf9\u7aef\u5173\u95ed\uff0c\u6211\u4eec\u4fbf\u9700\u8981\u505a\u4e00\u4e9b\u5bf9\u5e94\u7684\u5904\u7406\u3002<\/p>\n<p>\u5728\u7528 rust \u5b9e\u73b0\u7684\u8fde\u63a5\u6c60\u4e2d\uff0c\u8fde\u63a5\u672c\u8eab\u901a\u5e38\u4f1a\u88ab\u5199\u6210 future\uff0c\u5e76\u88ab\u7528\u4e8e <code>tokio::spawn<\/code>\u3002\u5f53\u8fd9\u4e2a future \u611f\u77e5\u5230\u8fde\u63a5\u65ad\u5f00\uff0c\u5219\u9700\u8981\u7528\u4e00\u4e9b\u624b\u6bb5\u6765\u901a\u77e5\u5176\u4ed6\u65b9\u9762\uff0c\u6b64\u65f6\u6211\u4eec\u4fbf\u9700\u8981\u5728 <code>Notify<\/code> \u548c <code>oneshot::channel<\/code> \u4e2d\u505a\u51fa\u9009\u62e9\u3002<\/p>\n<p>\u4e0b\u9762\u6211\u4eec\u7b80\u5355\u5199\u4e2a benchmark\uff0c\u7528 <code>tokio::sleep<\/code> \u6a21\u62df\u4e00\u5b9a\u65f6\u95f4\u540e\u7684\u8fde\u63a5\u65ad\u5f00\u3002<\/p>\n<h3>3.1. \u4ee3\u7801\u6e05\u5355<\/h3>\n<p>\u4e3b\u7a0b\u5e8f main.rs:<\/p>\n<pre><code class=\"language-rust\">use futures::{future::join_all, FutureExt};\nuse tokio::{\n    sync::oneshot::{channel, Receiver, Sender},\n    sync::Notify,\n    time::sleep,\n};\n\nuse std::{\n    future::{poll_fn, Future},\n    pin::Pin,\n    sync::Arc,\n    task::{Context, Poll},\n    time::{Duration, Instant},\n};\n\nstruct NotifyTester {\n    sleep: Pin&lt;Box&lt;tokio::time::Sleep&gt;&gt;,\n    drop_notifier: Arc&lt;Notify&gt;,\n}\n\nimpl NotifyTester {\n    fn start(not: Arc&lt;Notify&gt;) {\n        tokio::pin!(sleep);\n        let tester = Self {\n            sleep: Box::pin(sleep(Duration::from_secs(5))),\n            drop_notifier: not,\n        };\n        tokio::spawn(tester);\n    }\n}\n\nimpl Future for NotifyTester {\n    type Output = ();\n\n    fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;&#039;_&gt;) -&gt; Poll&lt;Self::Output&gt; {\n        let this = self.get_mut();\n        this.sleep.poll_unpin(cx)\n    }\n}\n\nimpl Drop for NotifyTester {\n    fn drop(&amp;mut self) {\n        self.drop_notifier.notify_one();\n    }\n}\n\npub(crate) async fn test_notify(concurrent: usize) {\n    let mut joins = Vec::new();\n    for _ in 0..concurrent {\n        let notify = Arc::new(Notify::new());\n\n        NotifyTester::start(notify.clone());\n        joins.push(tokio::spawn(async move { notify.notified().await }));\n    }\n    join_all(joins.into_iter()).await;\n}\n\nstruct ChannelTester {\n    sleep: Pin&lt;Box&lt;tokio::time::Sleep&gt;&gt;,\n    _drop_notifier: Sender&lt;()&gt;,\n}\n\nimpl ChannelTester {\n    fn start() -&gt; Receiver&lt;()&gt; {\n        let (tx, rx) = channel();\n        let tester = Self {\n            sleep: Box::pin(sleep(Duration::from_secs(5))),\n            _drop_notifier: tx,\n        };\n        tokio::spawn(tester);\n        rx\n    }\n}\n\nimpl Future for ChannelTester {\n    type Output = ();\n\n    fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;&#039;_&gt;) -&gt; Poll&lt;Self::Output&gt; {\n        let this = self.get_mut();\n        this.sleep.poll_unpin(cx)\n    }\n}\n\npub(crate) async fn test_channel(concurrent: usize) {\n    let mut joins = Vec::new();\n    for _ in 0..concurrent {\n        let mut rx = ChannelTester::start();\n        joins.push(tokio::spawn(poll_fn(move |cx| rx.poll_unpin(cx))));\n    }\n    join_all(joins.into_iter()).await;\n}\n\nconst CONCURRENT_COUNT: u32 = 500_000;\n\n#[tokio::main]\nasync fn main() {\n    \/\/ let now = Instant::now();\n    \/\/ test_notify(CONCURRENT_COUNT as usize).await;\n    \/\/ let elapsed = now.elapsed();\n    \/\/ println!(&quot;notify need {elapsed:?}&quot;);\n\n    let now = Instant::now();\n    test_channel(CONCURRENT_COUNT as usize).await;\n    let elapsed = now.elapsed();\n    println!(&quot;oneshot_channel need {elapsed:?}&quot;);\n}\n<\/code><\/pre>\n<h3>3.2. \u6d4b\u8bd5\u7ed3\u679c<\/h3>\n<p>\u7531\u4e8e\u6211\u4eec\u5728\u4ee3\u7801\u4e2d\u6a21\u62df\u8fde\u63a5\u4fdd\u6d3b\u65f6 sleep \u4e86 5s\uff0c\u56e0\u6b64\u6700\u540e\u8ba1\u7b97\u8017\u65f6\u65f6\u9700\u8981\u51cf\u53bb\u3002\u5b9e\u9a8c\u7ed3\u679c\u5982\u4e0b\uff1a<\/p>\n<table>\n<thead>\n<tr>\n<th style=\"text-align: center;\">\u5b9e\u4f8b\u4e2a\u6570<\/th>\n<th style=\"text-align: center;\">Notify \u8017\u65f6<\/th>\n<th style=\"text-align: center;\">oneshot channel \u8017\u65f6<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">10000<\/td>\n<td style=\"text-align: center;\">21ms<\/td>\n<td style=\"text-align: center;\">19ms<\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\">50000<\/td>\n<td style=\"text-align: center;\">93ms<\/td>\n<td style=\"text-align: center;\">94ms<\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\">100000<\/td>\n<td style=\"text-align: center;\">179ms<\/td>\n<td style=\"text-align: center;\">192ms<\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\">500000<\/td>\n<td style=\"text-align: center;\">941ms<\/td>\n<td style=\"text-align: center;\">944ms<\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\">1000000<\/td>\n<td style=\"text-align: center;\">1816ms<\/td>\n<td style=\"text-align: center;\">1904ms<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>3.3. \u7ed3\u8bba<\/h3>\n<p>\u5b9e\u9a8c\u53ef\u89c1\uff0c\u4e8c\u8005\u7684\u6027\u80fd\u5176\u5b9e\u6bd4\u8f83\u63a5\u8fd1\u3002\u56e0\u6b64\uff0c\u5728\u4e8c\u8005\u95f4\u505a\u51fa\u9009\u62e9\u65f6\uff0c\u4e3b\u8981\u8fd8\u662f\u6839\u636e\u5e94\u7528\u573a\u666f\u7684\u9700\u6c42\u6765\u5224\u65ad\uff0c\u4f8b\u5982\u662f\u5426\u9700\u8981\u5728\u901a\u77e5\u65f6\u643a\u5e26\u6570\u636e\u3001\u662f\u5426\u9700\u8981\u591a\u4e2a\u7b49\u5f85 \/ \u5524\u9192\u65b9\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. \u5171\u6027\u4e0e\u533a\u522b \u5199\u5f02\u6b65 rust \u65f6\uff0c\u6211\u4eec\u7ecf\u5e38\u9700\u8981\u4e00\u79cd\u4e00\u6b21\u6027\u7684\u901a\u77e5\u624b\u6bb5\uff0c\u7528\u4e8e\u5b9e\u73b0\u7ebf\u7a0b\u540c\u6b65\u3002tokio \u63d0\u4f9b\u4e86 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[24,26],"class_list":["post-376","post","type-post","status-publish","format-standard","hentry","category-rust","tag-rust","tag-tokio"],"_links":{"self":[{"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/posts\/376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/comments?post=376"}],"version-history":[{"count":0,"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/posts\/376\/revisions"}],"wp:attachment":[{"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/media?parent=376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/categories?post=376"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cococat.top\/index.php\/wp-json\/wp\/v2\/tags?post=376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}