OpenMP将函数的执行分配给线程
OpenMP assign the execution of a function to a thread?
基本上,我需要主线程根据一些全局变量的值继续进行一些操作,这些全局变量可以由辅助线程编辑(以某些选定的间隔)。类似:
vector<int> mySharedVar;
void secondaryThreadFunction() {
Do some operations
And update mySharedVar if necessarily
}
int main() {
int count = 0;
while(true) {
count++;
if (count%100) { //> Each 100 iterations run a parallel thraed
//> RUN secondaryThreadFunction in a separateThread
}
this is the main thread that based its operation on mySharedVar
}
}
用secondaryThreadFunction();
运行单个并行线程的openmp命令是什么?
还有比这更好的方法吗:
#pragma omp parallel num_threads(2)
{
int i = omp_get_thread_num();
if (i == 0){
mainThread();
}
if (i == 1 || omp_get_num_threads() != 2){
secondaryThreadFunction();
}
}
以下是我的想法:
#include <omp.h>
#include <unistd.h>
#include <vector>
#include <iostream>
std::vector<int> mySharedVar(10);
void secondaryThreadFunction() {
mySharedVar[5]++;
}
int main() {
int i = 0 ;
#pragma omp parallel sections shared(mySharedVar) private(i)
{
#pragma omp section
//main thread
{
while( mySharedVar[5] < 10) {
std::cout << "main: ";
for(i=0; i < mySharedVar.size(); ++i){
std::cout << mySharedVar[i] << " ";
}
std::cout << std::endl;
usleep(1.e5); // wait 0.1 seconds
}
}
#pragma omp section
{
while( mySharedVar[5] < 10) {
secondaryThreadFunction();
usleep(3.e5); // wait 0.3 seconds
}
}
}
}
用g++ -fopenmp test_omp_01.cc && ./a.out
编译和运行
输出:
main: 0 0 0 0 0 1 0 0 0 0
main: 0 0 0 0 0 1 0 0 0 0
main: 0 0 0 0 0 1 0 0 0 0
main: 0 0 0 0 0 2 0 0 0 0
main: 0 0 0 0 0 2 0 0 0 0
main: 0 0 0 0 0 2 0 0 0 0
main: 0 0 0 0 0 3 0 0 0 0
main: 0 0 0 0 0 3 0 0 0 0
main: 0 0 0 0 0 3 0 0 0 0
main: 0 0 0 0 0 4 0 0 0 0
main: 0 0 0 0 0 4 0 0 0 0
main: 0 0 0 0 0 4 0 0 0 0
main: 0 0 0 0 0 5 0 0 0 0
main: 0 0 0 0 0 5 0 0 0 0
main: 0 0 0 0 0 5 0 0 0 0
main: 0 0 0 0 0 6 0 0 0 0
main: 0 0 0 0 0 6 0 0 0 0
main: 0 0 0 0 0 6 0 0 0 0
main: 0 0 0 0 0 7 0 0 0 0
main: 0 0 0 0 0 7 0 0 0 0
main: 0 0 0 0 0 7 0 0 0 0
main: 0 0 0 0 0 8 0 0 0 0
main: 0 0 0 0 0 8 0 0 0 0
main: 0 0 0 0 0 8 0 0 0 0
main: 0 0 0 0 0 9 0 0 0 0
main: 0 0 0 0 0 9 0 0 0 0
main: 0 0 0 0 0 9 0 0 0 0
相关文章:
- 应该将线程分配给堆栈还是堆?
- 将正常函数的工作分配给多个线程是否安全
- 在std::线程中使用已分配的结构数据
- 在可拆卸线程完成操作时取消分配内存
- 在线程退出之前,线程分配的内存块是否与线程本身具有相同的相关性?
- 如何使用boost.thread运行多个接收器,每个线程应该分配给每个接收器?
- 线程函数无法从堆上分配的缓冲区中读取字符
- COPY分配被禁用于C 11中的线程
- 根据不同的硬件在任意数量的线程上分配 for 循环
- 重新分配独立的boost ::线程安全吗?
- c++ 中的每个线程都有自己的内存分配限制吗?
- C++多线程:线程安全的内存分配
- 将分配到std :: vector元素线程安全
- 内存分配对多线程性能的影响
- 堆上的多线程(DE)分配
- 线程的静态与动态内存分配
- 将数组分配在固定数量的线程之间
- C++ stl unordered_map,线程安全,其中每个线程仅访问其自己分配的键,并且可以编辑该值
- 如何分配线程本地存储
- CUDA:在2D网格中分配线程ID