在没有锁的x86机器上读/写一个int [英] Read/Write an int on x86 machine without lock

查看:151
本文介绍了在没有锁的x86机器上读/写一个int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在C程序中,我有一个在32位机器上运行的P线程, int MAX - 一个共享的32位整数

Suppose in a C program I have P threads running on a 32 bit machine, and int MAX--a shared 32-bit integer

每个线程都可以读/写MAX。

Each thread can read/write to MAX.

要求:线程读取的值不应该被破坏,例如第一个16位和最后一个16位不同步

Requirement: the value a thread read should not be corrupted, e.g first 16bit and last 16bit are out of sync

问题:我需要锁定才能保护读写?

Question: Do I need a lock to protect the read and write? or Can I safely ignore the lock, because LOAD/SAVE assembly instruction is guaranteed to happen atomically?

推荐答案

读写操作是原子操作的,因为LOAD /当int正确对齐。它不能跨越缓存行的结尾。高速缓存行为64字节。大多数任何编译器都确保对齐方式是可以处理的,但它可以被覆盖,例如一个结构包装pragma。

Reads and writes are atomic when the int is aligned properly. It cannot straddle the end of a cache line. A cache line is 64 bytes. Most any compiler ensures the alignment is taken care of but it can be overridden with, say, a structure packing pragma.

是的,你需要一个锁来保护值线程执行读 - 修改 - 写操作。你可以从InterlockedXxxx得到一个便宜的。

Yes, you need a lock to protect the value when threads perform a read-modify-write operation. You can get a cheap one from InterlockedXxxx, perhaps.

这篇关于在没有锁的x86机器上读/写一个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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