C ++多线程-锁定一个指针分配? [英] c++ multi threading - lock one pointer assignment?

查看:147
本文介绍了C ++多线程-锁定一个指针分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法

SomeStruct* abc;

void NullABC()
{
    abc = NULL;
}

这只是示例,并不十分有趣. 许多线程可以同时调用此方法. 我是否需要锁定"abc = NULL"行? 我认为它只是指针,因此可以一口气完成它,实际上并不需要它,只是想确定一下.

This is just example and not very interesting. Many thread could call this method at the same time. Do I need to lock "abc = NULL" line? I think it is just pointer so it could be done in one shot and there isn't really need for it but just wanted to make sure.

谢谢

推荐答案

这取决于您所运行的平台.在许多平台上,只要abc正确对齐,写入操作都是原子的.

It depends on the platform on which you are running. On many platforms, as long as abc is correctly aligned, the write will be atomic.

但是,如果您的平台没有这样的保证,则需要使用锁,原子变量或互锁操作来同步对变量的访问.

However, if your platform does not have such a guarantee, you need to synchronize access to the variable, using a lock, an atomic variable, or an interlocked operation.

这篇关于C ++多线程-锁定一个指针分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆