Skip to content

Commit 6134c34

Browse files
authored
cancel other tasks if joined (#402)
2 parents bf03c44 + 02f40a9 commit 6134c34

File tree

4 files changed

+36
-2
lines changed

4 files changed

+36
-2
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,20 @@ fn main() {
159159
}
160160
```
161161

162+
### wait until any task is completed or timed out
163+
164+
```rust
165+
#[open_coroutine::main]
166+
fn main() {
167+
let result = open_coroutine::any_timeout_join!(
168+
std::time::Duration::from_secs(1),
169+
open_coroutine::task!(|_| 1, ()),
170+
open_coroutine::task!(|_| 2, ()),
171+
open_coroutine::task!(|_| 3, ())
172+
).expect("timeout");
173+
}
174+
```
175+
162176
### scalable stack
163177

164178
```rust

README_ZH.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,20 @@ fn main() {
155155
}
156156
```
157157

158+
### 等待任一任务完成或超时
159+
160+
```rust
161+
#[open_coroutine::main]
162+
fn main() {
163+
let result = open_coroutine::any_timeout_join!(
164+
std::time::Duration::from_secs(1),
165+
open_coroutine::task!(|_| 1, ()),
166+
open_coroutine::task!(|_| 2, ()),
167+
open_coroutine::task!(|_| 3, ())
168+
).expect("timeout");
169+
}
170+
```
171+
158172
### 可伸缩栈
159173

160174
```rust

core/src/co_pool/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ impl<'p> CoroutinePool<'p> {
255255
return;
256256
}
257257
_ = self.no_waits.insert(Box::leak(Box::from(task_name)));
258+
_ = CANCEL_TASKS.remove(task_name);
258259
}
259260

260261
/// Use the given `task_name` to obtain task results, and if no results are found,

open-coroutine/src/lib.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,12 @@ impl<R> JoinHandle<R> {
203203
}
204204

205205
pub fn any_join<I: IntoIterator<Item = Self>>(iter: I) -> std::io::Result<Option<R>> {
206-
Self::any_timeout_join(Duration::MAX, Vec::from_iter(iter).as_slice())
206+
let vec = Vec::from_iter(iter);
207+
Self::any_timeout_join(Duration::MAX, &vec).inspect(|_| {
208+
for handle in vec {
209+
_ = handle.try_cancel();
210+
}
211+
})
207212
}
208213

209214
pub fn try_cancel(self) -> std::io::Result<()> {
@@ -239,7 +244,7 @@ impl<R> Deref for JoinHandle<R> {
239244
#[macro_export]
240245
macro_rules! any_timeout_join {
241246
($time:expr, $($x:expr),+ $(,)?) => {
242-
$crate::JoinHandle::any_timeout_join($time, vec![$($x),+].as_slice())
247+
$crate::JoinHandle::any_timeout_join($time, &vec![$($x),+])
243248
}
244249
}
245250

0 commit comments

Comments
 (0)