基本上我需要Master线程继续根据一些全局变量的值来做一些操作,这些变量可以由一个辅助线程编辑(在某些选定的时间间隔)。喜欢的东西:
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();
}
}
答案 0 :(得分:1)
以下是我提出的建议:
#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