【问题标题】:What is the best way to declare function variables when called by multiple threads?当被多个线程调用时,声明函数变量的最佳方法是什么?
【发布时间】:2016-11-21 08:02:16
【问题描述】:

有一个函数必须运行很长时间。 假设该函数被多个线程调用。该函数有许多变量,其中大多数是 std::string。 有两种可能的方式来声明函数变量: 1-

 void Test()
 {
    std::string s1; s1.reserve(500);
    std::string s2; s2.reserve(500);
    std::string s3; s3.reserve(500);
    std::string s4; s4.reserve(500);
    std::string s5; s5.reserve(500);

    for(;;)
    {
        s1= Read_from_file();
        s2= Read_from_file2();
        s3= s1.substr(0,Snaplength);
        s4= s2.substr(0,Snaplength);
        s5= s1+ s2;
        .
        .
        .       
    }

 }

2-

    for(;;)
    {
        std::string s1= Read_from_file();
        std::string s2= Read_from_file2();

        std::string s3= s1.substr(0,Snaplength);
        std::string s4= s2.substr(0,Snaplength);
        .
        .
        .       
    }

 }

如前所述,函数必须运行很长时间。

当我需要通过多个线程调用我的函数时,哪种方式在时间复杂度方面更好?

[添加:] 假设我需要调用我的函数 1000000 次,并希望尽可能快地完成它。一种可能的方法是通过多个线程运行该函数,但是 Afaik 并不总是可以通过多个线程运行该函数来获得更好的性能。在哪种情况下添加线程可能会更快?

操作系统= GNU/Linux

【问题讨论】:

  • 如果您使用的是 C++11,几乎可以肯定是第二个。
  • 局部变量不在线程之间共享,所以我不明白你在问什么。

标签: c++ multithreading operating-system


【解决方案1】:

就时间上的算法复杂度而言,没有区别;第二个版本可能(!)效率更高一些,但出于不同的原因,我更喜欢它:它缩小了变量的范围,从而改进了封装。

【讨论】:

    【解决方案2】:

    如果您希望它真正高效,请避免在堆栈上创建字符串完全。当您分配字符串时,它可能会执行需要同步的堆分配,并且会很慢。

    最快的方法是预先分配私有内存供每个线程使用,尽可能使用 memcpy 和类似的代替字符串。你真的需要这些字符串,还是只需要原始数据?

        std::string s1= Read_from_file();
        // can be replaced by
        fread(private_memory_area[thread_number], 1, datasize, file)
    
        std::string s3= s1.substr(0,Snaplength);
        // can be replaced by
        memcpy(private_memory_area_2[thread_number], private_memory_area[thread_number], Snaplength);
    

    抱歉,这看起来很复杂,但您要求它“尽可能快”,而 std::string 根本没有效率。如果字符串很大,使用这种方法是值得的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 2016-12-21
      • 2011-12-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多