繁体   English   中英

如何让两个线程通过指针交换数据?

[英]How to let two threads exchange data via a pointer?

我想要一个异步线程来编辑对象。 因此,我存储了一个指向该对象的指针。

Data *pointer;

还有一个类型为std::atomic<bool>的标志,用于知道辅助线程是否正在修改指针所指向的对象。 当该标志为true时,主线程将不会影响指针及其基础对象。

std::atomic<bool> modifying;

void Thread()
{
    // wait for jobs
    for(;;)
    {
        // the flag is set to true my the main thread
        // to let this thread start processing
        if(modifying)
        {
            // modify the object the pointer points to,
            // pass the pointer to a function to do so,
            // and so on...

            // the flag to false to tell the main thread
            // that it can read the result from the pointer
            // and prepare it for the next job
            modifying = false;
        }
    }
}
  • 如何确保线程安全?

我不能用std::atomic来包装指针,因为从辅助线程中,我需要将指针传递给需要非原子Data*类型作为参数的函数。

  • 指针是否需要专门声明为原子的? 我认为处理器不会在写入单个寄存器时更改线程。 还是我必须使其原子化以防止不必要的编译器优化?
  • 如果指针是原子的,则基础对象也是如此吗? 换句话说,我可以使用从pointer.load()获得的指针来修改对象吗?

感谢您的澄清。

听起来您想要拥有的特权是将对象编辑为互斥对象。 这正是互斥的目的。

通常,假设您有线程A和B,这两个线程都希望更新相同的指针。 例如,当A想要进行编辑时,它将尝试锁定()互斥量。 如果互斥锁尚未被B锁定,则此操作将成功,并且A可以执行其操作。 如果互斥已经被B锁定,然后将阻止(即,停止执行),直到B释放其对互斥锁 ,此时A将继续做它的东西是正常的。

对于C ++ 11互斥锁的语法的更具体示例,此页面做得很好: http : //en.cppreference.com/w/cpp/thread/mutex

而且,当然,我一般会建议使用pthreads库来解释互斥锁(以及其他线程概念): https : //computing.llnl.gov/tutorials/pthreads/#Mutexes

就您而言,您的代码可能看起来像这样:

std::mutex editing;

void Thread()
{
    for(;;)
    {
        editing.lock();

        // Do whatever editing you wanted to do here.

        editing.unlock();
    }
}

还应注意std :: mutex类上的try_lock()函数。 这与lock()非常相似,不同之处在于,如果互斥锁已被锁定,则它将仅返回false,表明无法获取该锁定,然后继续操作。 如果您希望线程只忘记编辑对象,而如果另一个线程已经在编辑对象,而不是等待另一个线程再进行编辑,则这将很有用。

暂无
暂无

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

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