[英]How to read lock a multithreaded C++ program
對於下面的帶有openMP的多線程程序,如何防止一個線程將一個線程寫入“ stuff”時其他線程讀取“ stuff”向量?
vector<int> stuff; //Global vector
void loop() {
#pragma omp parallel for
for(int i=0; i < 8000; i++){
func(i);
}
}
void func(int& i) {
vector<int> local(stuff.begin() + i, stuff.end()); //Reading and copying global vector "stuff"
//Random function calls here
#pragma omp critical
stuff.assign(otherstuff.begin(), otherstuff.end()); //Writing to global vector "stuff"
}
您可以使用互斥鎖來同步對多個線程之間共享的數據的訪問:
#include <mutex>
std::mutex g_stuff_mutex;
vector<int> stuff; //Global vector
void loop() {
#pragma omp parallel for
for(int i=0; i < 8000; i++){
func(i);
}
}
void func(int& i) {
g_stuff_mutex.lock();
vector<int> local(stuff.begin() + i, stuff.end()); //Reading and copying global vector "stuff"
g_stuff_mutex.unlock();
//Random function calls here
#pragma omp critical
g_stuff_mutex.lock();
stuff.assign(otherstuff.begin(), otherstuff.end()); //Writing to global vector "stuff"
g_stuff_mutex.unlock();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.