lundi 10 janvier 2022

Can multi-threading improve the performance definitely

I'm using C++11 to develop a project.

In some function, I got some parallel tasks as below:

void func() {
    auto res1 = task1();
    auto res2 = task2();
    auto res3 = task3();
    ...
    std::cout << res1 + res2 + res3 + ...;
}

Well, each task is a little heavy, let's say each task would spend 300ms.

Now I'm thinking that making each task to be a std::thread should improve the performance.

But as my understanding, it's the OS who schedules the threads. I'm not sure if the OS ensures that it will execute these threads immediately or it may need to wait for some other stuff?

So my question is if making the tasks multi-threading can definitely improve the performance, or in some cases, this method would get a worse performance?

BTW, I know that too many threads can cause a very bad performance because of context switch, in my real case, the counts of the tasks is less than 10 and they don't share any data.

Aucun commentaire:

Enregistrer un commentaire