Niko Matsakis
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# Writing doc workshop / 2021-03-30 ## Topic: C++ interop ### Interviewing pcwalton :) * FB has adopted the C++23 async networking proposals aggressively * Expectation is that other groups in industry will follow * All the networking code at FB is async * Polyglot company and a lot of stuff is giant binaries with many languages * C++ async: * Like Rust, no single executor, and there are multiple runtimes * FB's runtime is called Folly * large bundle of libraries based on libevent * libevent plays the role of a "reactor" in Rust parlance * C++ library comes with something called "static threadpool" just for scheduling work * What FB would like to do: * Folly executor be able to run Rust tasks * Just to avoid continuing to grow more and more threads * Have thousands of threads in their binaries (!) * Cleaner interop story, faster * Requires adapters * Q: Why not have C++ things run on a Rust runtime? * Would be a large change, millions of lines of C++ code * Everything is very tuned for FB's needs * Big difference between C++ and Rust * C++ is still under development, not yet stabilized * Rust has backwards compatibility requirements to consider * [WHAT IS HAPPENING](http://gph.is/1UOJYBT) * "Elephant in the room" Number 1 * Most FB I/O code doesn't run I/O on the main thread * It is proxied out to other threads * "Elephant in the room" Number 2 * I/O Uring is also something FB is focused on * This is also something that is in flux * Still opportunity to influence I/O Uring development * Working on adapter between C++ "future" * Really a "sender" and "receiver", in the C++ spec * Have created an adapter between C++ and Rust * Most important thing is to bridge C++'s callback-based model * C++ first defined async-await (called "coroutines") * Now they are defining the "Future" interfaces * There is some bridging needed * Coroutines * Standardized coawait, coreturn, coyield * General abstraction of which async I/O was envisioned to be one application * pcwalton still a bit fuzzy how they fit in * (require allocation in C++) * C++ executor proposal is more general in scope than Rust's executors * GPUs are explicitly part of the design * Rust is focused more on I/O, secondarily CPU * C++ model is callback based * Basic model is close to the API for futures many other languages have * You have a "sender" (future), which is an object that is created with a function that will be invoked when the value is ready ```cpp= std::static_thread_pool pool(16); std::executor auto ex = pool.executor(); std::sender auto begin = std::schedule(ex); std::sender auto hi_again = std::then(begin, []{ std::cout << "Hi again! Have an int."; return 13; }); std::sender auto work = std::then(hi_again, [](int arg) { return arg + 42; }); std::submit(work); ``` ```rust= // Rust-like C++ let sender0: impl Sender = ...; let sender1: impl Sender = std::then(sender0, callback) let sender2: impl Sender = std::then(sender1, ...) ``` * you can only use `then` on a given `sender` once. * receiver are a generalization of callbacks * have not only `on_success` but also `on_failure` * closures above are syntactic sugar for only having a success function * sender promises that it will invoke `success|failure` **exactly once** * cancellation is a WIP but there would be some other API for it * to submit a function to an executor you invoke `std::submit` and it happens asynchronously * executors can be set into "blocking mode" which causes them to block until completion * they also have eager vs non-eager, wherein it "immediately runs work that is submitting to it" * why separate senders and receivers? * reduces allocation somehow * how might one plausibly bridge these two? * two wrappers * C++ to Rust -- wraps a C++ `Sender` in something that can be polled * more important, you have a micro service written in Rust that wants to call C++ * you have to call the C++ function and give it a callback * this callback be called exactly once * Rust to C++ -- wraps a Rust future in a C++ sender (easy, in theory) * you own the future and hence you know that it won't be dropped * you poll it: * if it returns Ready * you need to create a Waker: * when the waker is called, it will schedule the a task to re-run the poll receiver * if the * Question: if you have to work this hard to use C++ and Rust, why use Rust in the first place? * Answer: some teams want to use Rust :) * Comes down to safety as the key selling point * Though there are productivity and quality-of-life enhancements (e.g., cargo, ADTs, match statements, rustfmt, etc) * Question: is FB only using Rust for Async I/O? * Answer: No, but it's a key use case. * Primary use case: using C++ libraries (like thrift) from within Rust ## C++ to Rust: * When you create the Rust future that wraps the C++ future * inside your C++ futures object, you have a field `the_poll_result: Option<Poll<T>>` that starts out as None * if it is None: * set this to `Some(Pending)`, call the C++ callback * return "not ready" * if it is Some: * C++ callback will have run, so just return it * When you get polled * a call to await * Rust is going to tell C++ function * call me back here when you have a result * return NotReady ```mermaid sequenceDiagram RustRuntime->>RustFuture: Poll! Note right of RustFuture: Store waker RustFuture->>CppSender: call me when you're ready RustFuture->>RustRuntime: return current value (NotReady) CppSender->>RustFuture: here is your result Note right of RustFuture: Store result RustFuture->>RustRuntime: I'm ready RustRuntime->>RustFuture: Poll! RustFuture->>RustRuntime: here is value ``` Going to need something like * detach on cancel * "if this is canceled, run it to completion" * part of Folly * challenge: there are some C++ sender APIs that take out parameters as references * e.g. reading into a buffer * if that gets dropped, could try to write into freed memory * have to move all of those references into the C++ sender * one solution: * have a staging copy inside the C++ sender * don't directly give out references into the RustFuture * when Rust polls you, copy/move out from there * kind of an FFI layer problem * correct place to solve this might be in cxx * basically part of the ABI between a Rust future and a C++ sender * cannot have references directly into a Rust future * FFI generators should automatically create these staging copies * maybe compiler can communicate to the FFI layer that there is a context where things can't be dropped * cases where we could avoid the copy: * running on an executor which won't drop except on abort * if future is not running on an executor, but it could be polled, bad stuff can happen * calling `select` drops the other futures, so that is a common way this happens in application code * useful idiom * you can implement timeouts this way * select on the io + a timer future * Q: how prevelant is select in practice? * unknown * connected to I/O uring * [notes on I/O uring](https://without.boats/blog/io-uring/) * note that I/O uring is working on having the kernel take ownership of buffers * plausible sketch * `unsafe fn poll_no_drop` --- https://nikomatsakis.github.io/wg-async-foundations/vision/status_quo/template.html * story sketch * Character? * Grace-- * sees the situation and FB and need to interop * teams want to use it etc * expects eventually all components will need to talk to one another * going to need to call libraries written in C++ * toys with the design * ultimately realizes that it's fairly easy except for out references * for that you need to move ownrship of the buffers into the future * reminds her of io-uring and she finds boats's blog post * morals? * Grace

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully