std :: vector <std :: mutex>坚持优化

时间:2015-06-05 14:19:53

标签: c++ arrays optimization mutex

我编写了一个使用大规模并行执行的程序。我正在使用一组对象和一组互斥用于同步。我的代码看起来像这样:

std::vector<MyObject> objects;
std::vector<std::mutex> mutexes;

void work(int data)
{
    for(unsigned int i = 0; i < objects.size(); ++i)
    {
        //Check if data Needs to be processed for objects[i]
        if(dontNeedToProcess)continue;

        mutexes[i].lock();
        //Work with data for objects[i]
        mutexes[i].unlock();
    }
}

函数“work”由具有不同数据的多个线程调用。几个小时后(有时甚至几天)程序被卡住了。当我使用gdb运行它时,我可以看到程序在锁定互斥锁时挂起。

现在的问题是我用优化(-O2)编译了progrem,并且互斥锁和“i”被优化了。

使用互斥体数组时,优化是否可能导致此行为?

编辑: 所有线程都在同一个位置。 Backtrace如下所示:

#0  0xb7779d3c in __kernel_vsyscall ()
#1  0xb67ff672 in __lll_lock_wait ()
    at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/lowlevellock.S:144
#2  0xb67fb1c2 in _L_lock_920 ()
   from /lib/i386-linux-gnu/i686/cmov/libpthread.so.0
#3  0xb67fb043 in __GI___pthread_mutex_lock (mutex=0x9de56530)
    at ../nptl/pthread_mutex_lock.c:114
#4  0xb69043c4 in pthread_mutex_lock (mutex=0x9de56530) at forward.c:192
#5  0xb72754f3 in pthread_mutex_lock ()
   from /usr/lib/i386-linux-gnu/libasan.so.1
#6  0x0809ac85 in __gthread_mutex_lock (__mutex=<optimized out>)
    at /usr/include/i386-linux-gnu/c++/4.9/bits/gthr-default.h:748
#7  lock (this=<optimized out>) at /usr/include/c++/4.9/mutex:135
...

0 个答案:

没有答案