Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use threads instead loop #2

Open
RodrigoDornelles opened this issue Oct 28, 2024 · 0 comments
Open

use threads instead loop #2

RodrigoDornelles opened this issue Oct 28, 2024 · 0 comments
Labels
help wanted Extra attention is needed

Comments

@RodrigoDornelles
Copy link
Owner

I'm a beginner in C++, the solution I was trying was having race conditions problems.

int
main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cerr << "command list:";
        for (const auto &command : commands_list) {
            std::cerr << " " << command.first;
        }
        std::cerr << std::endl;
        return 1;
    }

    std::vector<decltype(commands_list.begin())> commands;
    std::vector<std::stringstream> pipes(argc - 2);
    std::vector<std::thread> threads;

    for (int i = 1; i < argc; ++i) {
        auto command = commands_list.find(argv[i]);
        if (command == commands_list.end()) {
            std::cerr << "Command not found: " << argv[i] << std::endl;
            return 1;
        }
        commands.push_back(command);
    }

    for (size_t i = 0; i < commands.size(); ++i) {
        auto command = commands[i];
        std::istream &pipe_in = (i == 0) ? std::cin : pipes[i - 1];
        std::ostream &pipe_out = (i + 1 == commands.size()) ? std::cout : pipes[i];
        threads.emplace_back(command->second, std::ref(pipe_in), std::ref(pipe_out));
    }
    for (auto &thread : threads) {
        thread.join();
    }
    return 0;
}
@RodrigoDornelles RodrigoDornelles added the help wanted Extra attention is needed label Oct 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant