C++ 异步编程

                     

贡献者: addis

  • 本文处于草稿阶段。

   和 JavaScript 异步编程类似,c++ 使用异步编程可以执行某个任务而不等其返回就继续执行其他任务。例如读写文件。

#include <iostream>
#include <fstream>
#include <string>
#include <future>

// Function to write data to a file
void writeFile(const std::string& filename, const std::string& data) {
    std::ofstream file(filename);
    if (file.is_open()) {
        file << data;
        file.close();
    } else {
        throw std::runtime_error("Unable to open file");
    }
}

int main() {
    std::string filename = "example.txt";
    std::string data =
        "Hello, this is some text to write in the file asynchronously.";

    // Launch writeFile in an asynchronous manner
    std::future<void> result = std::async(std::launch::async, writeFile,
        filename, data);

    // Do other stuff here if needed
    std::cout << "Writing to the file asynchronously..." << std::endl;

    // Wait for the async task to finish and handle exceptions
    try {
        // This will rethrow any exception caught in the async task
        result.get();
        std::cout << "File written successfully." << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}
其中的 std::launch::async 让系统用另一个线程马上开始处理 writeFile,而如果换成 std::launch::deferred,则只用一个线程,只是等到 .get() 的时候再处理(类似 JS)。无论哪种,std::async() 都会立即返回(non-blocking)而不是任务完成再返回。

                     

© 小时科技 保留一切权利