c++ - 线程未能影响性能

标签 c++ multithreading c++11

下面是一个小程序,用于并行化 1/(n^2) 级数的近似值。请注意全局参数 NUM_THREADS

我的问题是,将线程数从 1 增加到 4(我的计算机的处理器数是 4)不会显着影响计时实验的结果。您是否看到 ThreadFunction 中存在逻辑缺陷?是否存在导致序列化执行的错误共享或错位阻塞?

#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <string>
#include <future>
#include <chrono>

std::mutex sum_mutex;           // This mutex is for the sum vector
std::vector<double> sum_vec;    // This is the sum vector
int NUM_THREADS = 1;
int UPPER_BD = 1000000;

/* Thread function */
void ThreadFunction(std::vector<double> &l, int beg, int end, int thread_num)
{
    double sum = 0;
    for(int i = beg; i < end; i++) sum += (1 / ( l[i] * l[i]) );
    std::unique_lock<std::mutex> lock1 (sum_mutex, std::defer_lock);
    lock1.lock();
    sum_vec.push_back(sum);
    lock1.unlock();
}

void ListFill(std::vector<double> &l, int z)
{
    for(int i = 0; i < z; ++i) l.push_back(i);
}

int main() 
{
    std::vector<double> l;
    std::vector<std::thread> thread_vec;

    ListFill(l, UPPER_BD);
    int len = l.size();

    int lower_bd = 1;
    int increment = (UPPER_BD - lower_bd) / NUM_THREADS;
    for (int j = 0; j < NUM_THREADS; ++j)
    {
        thread_vec.push_back(std::thread(ThreadFunction, std::ref(l), lower_bd, lower_bd + increment, j));
        lower_bd += increment;
    }

    for (auto &t : thread_vec) t.join();
    double big_sum;
    for (double z : sum_vec) big_sum += z;

    std::cout << big_sum << std::endl;

    return 0;
}

最佳答案

通过查看您的代码,我怀疑 ListFill 花费的时间比 ThreadFunction 长。为什么将值列表而不是每个线程应该循环的边界传递给线程?像这样的东西:

void ThreadFunction( int beg, int end ) {
    double sum = 0.0;
    for(double i = beg; i < end; i++) 
         sum += (1.0 / ( i * i) );
    std::unique_lock<std::mutex> lock1 (sum_mutex);
    sum_vec.push_back(sum);
}

为了最大化并行性,您需要将尽可能多的工作推送到线程上。参见 Amdahl's Law

关于c++ - 线程未能影响性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25086700/

相关文章:

c++ - 将通用文件包含在一个头文件中有什么好处?

c++ - 函数的 C/C++ 内存管理

C#为所有对象订阅相同的事件处理程序是否线程安全

multithreading - Locator.geocode(...) 卡住/阻止 OS 5 设备(Blackberry Java)中的 UI

c++ - 没有用于调用 boost::condition_variable::wait 的匹配函数

c++ - 在函数 : Invalid address specified to RtlValidateHeap 中使用 delete[]

c - fork进程是C中多线程的一个例子吗?

c++ - 我可以判断是否实现了 C++ 虚函数吗

c++11 - 将 std::vector 扩展到参数包中

c++ - Dave Abrahams 和 Chris Diggins 的 C++ 接口(interface)思想有哪些现代替代方案