【问题标题】:why ostringstream could not work well in multithreading environment为什么 ostringstream 在多线程环境中不能正常工作
【发布时间】:2010-09-14 08:15:13
【问题描述】:

也许有些奇怪。当我在我的多线程环境中使用 STL ostringstream 类时,我发现每个线程的执行时间随着线程数的增加而线性增加。我不知道为什么会这样。我尝试检查 ostringstream 源代码,但找不到任何同步代码。 ostringsstream 中是否有一些同步位置?我用 snprintf 替换 ostringsstream 并且性能大大提高。我的操作系统是 RHEL5.4 64BIT,我的服务器上有两个至强 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;
}

【问题讨论】:

  • 您检查过 CPU 利用率吗?如果两个 CPU 都 100% 忙碌,那么您的服务器就无法同时处理那么多线程。如果不是,则可能确实涉及锁争用。
  • 同步在 ostringstream 使用的语言环境类中,但我不确定如何删除这种依赖关系。

标签: c++ linux multithreading stl pthreads


【解决方案1】:

这似乎是一个已知问题。 Here 是 MSVC 的解决方案:静态链接。也许这也适用于 linux。

或者(建议用于 Sun Studio here),将流设为本地线程(而不是进程本地),以防止它们在其他线程访问它们时被每个线程锁定。

【讨论】:

    【解决方案2】:

    Ostringstream 在堆上分配内存。操作系统动态分配可能受互斥体保护吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 2019-11-20
      • 2013-01-08
      相关资源
      最近更新 更多