C ++ Pthreads - 多线程比单线程慢 [英] C++ Pthreads - Multithreading slower than single-threading

查看:1029
本文介绍了C ++ Pthreads - 多线程比单线程慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个C ++应用程序,使用pthreads库。程序中的每个线程访问一个公共的unordered_map。程序运行速度较慢,4线程比1.我注释了所有的代码在线程,并留下了标记化一个字符串的部分。仍然单线程执行更快,所以我得出的结论是,地图不是问题。
之后,我打印到屏幕线程的Id,它们似乎按顺序执行。

I am developing a C++ application, using pthreads library. Every thread in the program accesses a common unordered_map. The program runs slower with 4 threads than 1. I commented all the code in thread, and left only the part that tokenizes a string. Still the single-threading execution is faster, so I came to the conclusion that the map wasn't the problem. After that I printed to the screen the threads' Ids, and they seemed to execute sequentially.

在调用线程的函数中,我有一个循环,它在数组中创建线程,其大小是线程数(我们说'tn')。并且每次创建线程时,我执行一个for循环来连接它们。 (pthread_join)。

In the function that calls the threads, I have a while loop, which creates threads in an array, which size is the number of threads (let's say 'tn'). And every time tn threads are created, I execute a for loop to join them. (pthread_join). While runs many times(not only 4).

可能有什么问题?

推荐答案

如果你正在运行一个小的程序,这往往是这样的情况,因为工作启动线程,调度优先级,运行,上下文切换,然后同步可能实际上需要更多的时间,然后运行它作为一个单一的进程。

If you are running a small trivial program this tends to be the case because the work to start the threads, schedule priority, run, context switch, then sync could actually take more time then running it as a single process.

这里的要点是,当处理微不足道的问题时,它可以运行得更慢。但另一个因素可能是你实际在CPU中有多少内核。

The point here is that when dealing with trivial problems it can run slower. BUT another factor might be how many cores you actually have in your CPU.

这篇关于C ++ Pthreads - 多线程比单线程慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆