为什么ostringstream在多线程环境下不能很好的工作

2024-04-13

也许有些事情很奇怪。当我在多线程环境中使用STL ostringstream 类时,我发现每个线程的执行时间随着线程数量的增加而线性增加。我不知道为什么会这样。我尝试检查 ostringstream 源代码,但找不到任何同步代码。 ostringsstream中有一些同步的地方吗?我用 snprintf 替换了 ostringsstream,性能大大提高。我的操作系统是 RHEL5.4 64BIT,我的服务器上有两个 xeon 5620 cpu。

以下是运行结果 我分别使用 1 和 8 线程进行 1000000 个循环。左列是 threadid,右列是 运行时间。因此,很明显,随着线程数量的增加,每个线程的运行时间也会增加。

[host]$./multi_thread  1 1000000
1115760960:0.240113
[host]$./multi_thread  8 1000000
1105004864:8.17012
1115494720:8.22645
1125984576:8.22931
1136474432:8.41319
1094252864:8.73788
1167944000:8.74504
1157454144:8.74951
1146964288:8.75174

代码如下

#include <iostream>
#include <sstream>
using namespace std;

void * func(void * t)
{
        int n = *((int *) t);
        pthread_t pid = pthread_self();
        timeval t1, t2;
        gettimeofday(&t1, 0);
        for(int i = 0; i < n; i++)
        {
                ostringstream os;
                /*
                   char buf[255];
                   int ret = snprintf(buf, 30, "%d", 2000000);
                   buf[ret] = 0;
                 */
        }
        gettimeofday(&t2, 0);
#define DIFF(a, b) ((b.tv_sec - a.tv_sec) + (b.tv_usec - a.tv_usec) / 1000000.0)
        std::cout << pid << ":" << DIFF(t1, t2) << std::endl;
#undef DIFF

        return NULL;
}

int main(int argc, char *argv[])
{
        int m, n =0;
        m = atoi(argv[1]);
        n = atoi(argv[2]);
        pthread_t tid[m];
        for(int i = 0; i < m; i++)
                pthread_create(&tid[i], NULL, func, &n);
        for(int i = 0; i < m; i++)
                pthread_join(tid[i], NULL);
        return 0;
}

这似乎是一个已知问题。Here http://www.codeguru.com/forum/archive/index.php/t-300583.htmlMSVC 的一个解决方案:静态链接。也许这也适用于Linux。

或者(建议用于 Sun Studiohere https://forums.embarcadero.com/thread.jspa;jsessionid=05BE8F8E7F40A2904A4E58DB02FE10F5?messageID=213206),使流成为本地线程(而不是进程本地),以防止它们在其他线程访问它们时被每个线程锁定。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么ostringstream在多线程环境下不能很好的工作 的相关文章

随机推荐