Skip to content

I need your help in switching cpu-bound and io-bound tasks #32

Closed
@artemsazonov86

Description

@artemsazonov86

I read your documentation, but there are not enough examples, I would like to use your library to get something like this, as in the concurencpp library:

#include <cstring>
#include <fstream>
#include <iostream>
#include <vector>

#include "concurrencpp/concurrencpp.h"

concurrencpp::result<void> replace_chars_in_file(std::shared_ptr<concurrencpp::thread_pool_executor> background_executor,
                                                 std::shared_ptr<concurrencpp::thread_pool_executor> threadpool_executor,
                                                 const std::string file_path,
                                                 char from,
                                                 char to) {
    // switch control from whatever executor/thread this coroutine was called from to the background_executor.
    co_await concurrencpp::resume_on(background_executor);

    // we're running on the background executor now. we can safely block.
    std::vector<char> file_content;

    {
        std::ifstream input;
        input.exceptions(std::ifstream::badbit);
        input.open(file_path, std::ios::binary);
        file_content.assign(std::istreambuf_iterator<char>(input), {});
    }

    // switch execution to the threadpool-executor
    co_await concurrencpp::resume_on(threadpool_executor);

    // we're running on the threadpool executor now. we can process CPU-bound tasks now.
    for (auto& c : file_content) {
        if (c == from) {
            c = to;
        }
    }

    // switch execution back to the background-executor
    concurrencpp::resume_on(background_executor);

    // write the processed file content. since we're running on the background executor, it's safe to block.
    std::ofstream output;
    output.exceptions(std::ofstream::badbit);
    output.open(file_path, std::ios::binary);
    output.write(file_content.data(), file_content.size());

    std::cout << "file has been modified successfully" << std::endl;
}

Could you please give an example of similar code for your library?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions