Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading for loop in C++

I've got the following code and I'm attempting to add threading so it executes faster but I'm really stumped. I basically want different threads to execute different iterations of the for loop to speed up the process since I'll be pinging a lot of urls. However, I wasn't sure how to do that or if it was possible so I did what is seen below but I get an error at "thread doStuff(exec" right at the exec part that says there is no instance of constructor "std::thread::thread" matches the argument list. How can I apply threading to this situation when the value of the parameter for the "exec" function is changing at every iteration of the for loop?

On a side note, if you couldn't tell, I need to put the result of the "exec" function into index i of the vector "work".

EDIT: The last function is supposed to look incomplete because I deleted code that was irrelevant to this problem.

vector<string> check(vector<string> url)
{

    vector<string> work;
    for (int i = 0; i < url.size(); i++)
    {
        string ping = "ping ";
        ping.append(url[i]);
        thread doStuff(exec,work.push_back(exec(ping.c_str())));

        cout << work[i] << endl;
    }

    return work;
}
std::string exec(const char* cmd) {
    string timeOut = "Request timed out";
    string reply = "Reply from";
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
            result += buffer.data();
    }
return result;
like image 715
Cole Avatar asked Jun 27 '26 12:06

Cole


2 Answers

Since you're using Visual Studio, you might want to consider parallel_for. Also, C++17 introduced the Parallelism TS, which is a work in progress attempt at standardizing parallel algorithms. This blog post gives a nice introduction to what features are available, and how you can try them out today.

like image 125
Tim Johns Avatar answered Jun 29 '26 01:06

Tim Johns


You can use std::async in for loop

auto handle = std::async(std::launch::async,exec,ping.c_str());
work.push_back(handle.get());

That should work.

like image 33
SaurabhS Avatar answered Jun 29 '26 01:06

SaurabhS