简体   繁体   English

我是否以线程安全的方式使用此双端队列?

[英]Am I using this deque in a thread safe manner?

I'm trying to understand multi threading in C++. 我试图了解C ++中的多线程。 In the following bit of code, will the deque 'tempData' declared in retrieve() always have every element processed once and only once, or could there be multiple copies of tempData across multiple threads with stale data, causing some elements to be processed multiple times? 在下面的代码中,retrieve()中声明的双端队列'tempData'将始终使每个元素处理一次且仅处理一次,还是在多个带有过时数据的线程中存在tempData的多个副本,从而导致某些元素被多次处理次? I'm not sure if passing by reference actually causes there to be only one copy in this case? 在这种情况下,我不确定通过引用传递是否真的导致只有一个副本?

static mutex m;

void AudioAnalyzer::analysisThread(deque<shared_ptr<AudioAnalysis>>& aq)
{

    while (true)
    {
        m.lock();
        if (aq.empty())
        {
            m.unlock();
            break;
        }
        auto aa = aq.front();
        aq.pop_front();
        m.unlock();

        if (false) //testing
        {
            retrieveFromDb(aa);
        }
        else
        {
            analyzeAudio(aa);
        }
    }
}

void AudioAnalyzer::retrieve()
{
    deque<shared_ptr<AudioAnalysis>>tempData(data);
    vector<future<void>> futures;
        for (int i = 0; i < NUM_THREADS; ++i)
    {
        futures.push_back(async(bind(&AudioAnalyzer::analysisThread, this, _1), ref(tempData)));
    }

    for (auto& f : futures)
    {
        f.get();
    }
}

Looks OK to me. 在我看来还可以。

Threads have shared memory and if the reference to tempData turns up as a pointer in the thread then every thread sees exactly the same pointer value and the same single copy of tempData. 线程具有共享内存,并且如果对tempData的引用作为线程中的指针出现,则每个线程将看到完全相同的指针值和相同的tempData单个副本。 [You can check that if you like with a bit of global code or some logging.] [您可以检查一下是否需要一些全局代码或一些日志记录。]

Then the mutex ensures single-threaded access, at least in the threads. 然后,互斥体至少在线程中确保单线程访问。


One problem: somewhere there must be a push onto the deque, and that may need to be locked by the mutex as well. 一个问题:在某处一定要推动双端队列,而这可能也需要由互斥锁锁定。 [Obviously the push_back onto the futures queue is just local.] [显然,将push_back推送到期货队列只是本地的。]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM