开发者

Stl container vector push_back with OpenMP multithreading

开发者 https://www.devze.com 2023-03-28 17:12 出处:网络
I want to push_back an object into a vector from different threads. The no. of threads depends on the machine.

I want to push_back an object into a vector from different threads. The no. of threads depends on the machine.

#开发者_JS百科pragma omp parallel shared(Spaces, LookUpTable) private(LutDistribution, tid)
{
    tid = omp_get_thread_num();

    BestCoreSpaces.push_back( computeBestCoreSpace(tid, &Spaces, &LookUpTable, LutDistribution));
}

The problem is, that I'm not sure if it's working. I don't get crashes. I'm using openMP. Is openMP queuing something? Maybe its enough to reserve memory for the container with BestCoreSpaces.reserve(tid) or to assign the amount of elements with BestCoreSpaces.assign(tid, Space). Can somebody help me?


You just get away with it - you have a race condition that might or might not manifest itself depending on the optimization level at compile time, the thread execution and/or the alignment of the stars.

You have to make the push_back() a critical section (i.e use a mutex). For example:

#pragma omp parallel shared(Spaces, LookUpTable, BestCoreSpaces) private(LutDistribution, tid)
{
  tid = omp_get_thread_num();
#pragma omp critical
  BestCoreSpaces.push_back( 
    computeBestCoreSpace(tid, &Spaces, &LookUpTable, LutDistribution)
  );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号