OpenMP 一次只执行一个线程
OpenMP executes only one thread at a time
这是我的代码:
template <unsigned int DIM>
MyVector<DIM> MyVector<DIM>::operator+(MyVector& other) {
MyVector ans = MyVector<DIM>();
#pragma omp parallel for
for (unsigned int i = 0; i < DIM; ++i)
{
std::cout << omp_get_thread_num() << std::endl;
ans.values_[i] = values_[i] + other.values_[i];
}
return ans;
}
其中values_是双精度模板化的 std::vector,DIM 类似于 1024。
我使用'g++ -std=c++14 -fopenmp -g'编译了它
。当我不使用 OpenMP 时,即使我有多个线程,我获得的性能也几乎没有区别。
确实,这句话:
std::cout << omp_get_thread_num() << std::endl;
显示线程一次执行一个...
输出很干净,类似于 11111...、22222...、00000...、33333...,htop 始终只显示一个 100% 的核心,在整个执行过程中是相同的。
我已经在几台具有多个发行版的机器上尝试过,它到处都是一样的。
您可能希望像这样重写代码,以防止 I/O 的巨大开销(也或多或少地序列化程序执行):
template <unsigned int DIM>
MyVector<DIM> MyVector<DIM>::operator+(MyVector& other) {
MyVector ans = MyVector<DIM>();
#pragma omp parallel
{
#pragma omp critical(console_io)
{
// The following are actually two function calls and a critical
// region is needed in order to ensure I/O atomicity
std::cout << omp_get_thread_num() << std::endl;
}
#pragma omp for schedule(static)
for (unsigned int i = 0; i < DIM; ++i)
{
ans.values_[i] = values_[i] + other.values_[i];
}
}
return ans;
}
确保DIM
既足够大,以便 OpenMP 的开销与正在完成的工作相比较小,同时又足够小,使向量适合 CPU 的最后一级缓存。一旦后者不再适用,您的循环就会受到内存限制,添加新线程不会加快计算速度。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- 在另一个线程中调用luaL_error会引发qWarning
- C++一个线程如何正确通信其任务已完成?
- 最佳做法是从另一个线程访问 qml 中的Q_PROPERTY
- C++线程:如何在一个线程仍在运行时阻止另一个线程执行 (Win32)
- 如何制作一个只能在一个线程上同时执行的函数?
- 结束另一个线程中使用的对象的生存期
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 一个线程等待多个线程事件
- 从不同进程中的另一个线程挂起/恢复线程或进程
- 我有一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)错误.我认为这是由于内存管理不好.我可以
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 计时器是否从另一个线程启动?
- 互斥,Windows 10,c ++,在一个线程上获取,在另一个线程上发布
- Qt 在另一个线程中无限循环
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 当只有一个线程主要使用该对象而其他线程很少使用它时,如何最小化该对象的互斥锁锁定?
- 从另一个线程发出信号是否安全?
- AMQP-CPP,libev >停止ev_loop来自另一个线程