gpt4 book ai didi

c++ - OpenMP 将函数的执行分配给线程?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:31:26 26 4
gpt4 key购买 nike

基本上我需要主线程根据一些全局变量的值继续执行一些操作,这些全局变量可以由辅助线程编辑(在某些选定的时间间隔内)。类似的东西:

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

关于c++ - OpenMP 将函数的执行分配给线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11538561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com