Home > Blockchain >  Can multi-threading improve the performance definitely
Can multi-threading improve the performance definitely

Time:01-10

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.

CodePudding user response:

If the threads are at kernel level which it think they are based on this. The threads are managed by the kernel and it could happend that a thread gets interrupted. But, that doesn't matter because if you don't use threads, the program can also be interrupted(probably, see this). But, since we assume the threads are kernel level, they have a bigger overhead for creating them and are slower overall. Though they can use multiple processors.


If the thread are at user level. The thread will be faster, but will only be able to use 1 processor. Further if the process is interrupted, everything is interrupted.


So to answer the question: no, multi-threading cannot definitely improve the performance. I think you just need to try with and without multithreading, and see what's the fastest.

  •  Tags:  
  • Related