简体   繁体   中英

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;

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM