async-rs / async-rs/async-std

Using write_vectored in spawned Future

Open
#751 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
4.1k
Forks
339
PR merge metrics
No merged PRs in 30d

Description

I was try to use some vectored write in a spawned task and was running into issues due to IoSlice not being Send
```
use async_std::task;
use futures::io::{AsyncWrite, AsyncWriteExt, IoSlice};

#[async_std::main]
async fn main() -> Result<(), Box> {
let mut writer: Vec = vec![];
task::spawn(async move {
my_write(&mut writer).await;
println!("{:?}", writer);
})
.await;
Ok(())
}

async fn my_write(writer: &mut W) {
let buf1 = [1; 8];
let buf2 = [2; 16];
let buf3 = [3; 8];
let bufs: [IoSlice; 3] = [
IoSlice::new(&buf1),
IoSlice::new(&buf2),
IoSlice::new(&buf3),
];

writer.write_vectored(&bufs[..]).await.unwrap();
}
```

The compiler error is -
```
error: future cannot be sent between threads safely
--> src/main.rs:7:5
|
7 | task::spawn(async move {
| ^^^^^^^^^^^ future is not `Send`
|
= help: within `[std::io::IoSlice<'_>]`, the trait `std::marker::Sync` is not implemented for `*mut std::ffi::c_void`
note: future is not `Send` as this value is used across an await
--> src/main.rs:25:5
|
25 | writer.write_vectored(&bufs[..]).await.unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^----^^^^^^^^^^^ - `bufs` is later dropped here
| | |
| | has type `&[std::io::IoSlice<'_>]`
| await occurs here, with `bufs` maybe used later
help: consider moving this into a `let` binding to create a shorter lived borrow
--> src/main.rs:25:28
|
25 | writer.write_vectored(&bufs[..]).await.unwrap();
```

What is the correct way to work around this ?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.