gcc 里提供了内置 CAS 函数:__atomic_compare_exchange_n(),它的基本用法如下:
Built-in Function: bool __atomic_compare_exchange_n (type *ptr, type *expected, type desired, bool weak, int success_memorder, int failure_memorder)
This built-in function implements an atomic compare and exchange operation. This compares the contents of
*ptrwith the contents of*expected. If equal, the operation is a read-modify-write operation that writes desired into*ptr. If they are not equal, the operation is a read and the current contents of*ptrare written into*expected. weak istruefor weak compare_exchange, which may fail spuriously, andfalsefor the strong

本文介绍了GCC中内置的原子比较并交换(CAS)函数__atomic_compare_exchange_n(),用于实现并发控制。通过示例展示了如何使用CAS函数创建spinlock,保证多线程环境下对共享资源的互斥访问。代码展示了如何在多线程程序中利用CAS进行同步,并最终达到无锁编程的效果。
最低0.47元/天 解锁文章
10万+

被折叠的 条评论
为什么被折叠?



