Skip to content

Instantly share code, notes, and snippets.

@vmrob
Created February 14, 2016 07:56
Show Gist options
  • Select an option

  • Save vmrob/ff20420a20c59b5a98a1 to your computer and use it in GitHub Desktop.

Select an option

Save vmrob/ff20420a20c59b5a98a1 to your computer and use it in GitHub Desktop.

Revisions

  1. vmrob renamed this gist Feb 14, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. vmrob created this gist Feb 14, 2016.
    31 changes: 31 additions & 0 deletions nonblocking
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    #include <iostream>
    #include <chrono>
    #include <future>
    #include <string>

    std::string GetLineFromCin() {
    std::string line;
    std::getline(std::cin, line);
    return line;
    }

    int main() {

    auto future = std::async(std::launch::async, GetLineFromCin);

    while (true) {
    if (future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
    auto line = future.get();

    // Set a new line. Subtle race condition between the previous line
    // and this. Some lines could be missed. To aleviate, you need an
    // io-only thread. I'll give an example of that as well.
    future = std::async(std::launch::async, GetLineFromCin);

    std::cout << "you wrote " << line << std::endl;
    }

    std::cout << "waiting..." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    }