首页 > 其他分享 >使用gcc内置CAS函数实现spinlock

使用gcc内置CAS函数实现spinlock

时间:2023-09-12 20:55:58浏览次数:39  
标签:__ gcc CAS lock ptr int slock memorder spinlock

 

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 *ptr with 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 *ptr are written into *expected. weak is true for weak compare_exchange, which may fail spuriously, and false for the strong variation, which never fails spuriously. Many targets only offer the strong variation and ignore the parameter. When in doubt, use the strong variation.

If desired is written into *ptr then true is returned and memory is affected according to the memory order specified by success_memorder. There are no restrictions on what memory order can be used here.

Otherwise, false is returned and memory is affected according to failure_memorder. This memory order cannot be __ATOMIC_RELEASE nor __ATOMIC_ACQ_REL. It also cannot be a stronger order than that specified by success_memorder.

 

#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>
 
#define THREAD_NUM 32 
 
volatile unsigned int sum = 0;
unsigned int max = 10000000; 
volatile bool cond = true;
 
typedef int slock_t;
 
static __inline__ int
cas(volatile slock_t *lock)
{
  slock_t expected = 0;
  return !(__atomic_compare_exchange_n(
		lock, &expected, (slock_t)1, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE));
}
 
#define S_UNLOCK(lock) __atomic_store_n(lock, (slock_t)0, __ATOMIC_RELEASE)
#define S_INIT_LOCK(lock) S_UNLOCK(lock)
#define SPIN(lock)  (*(lock) ? 1 : cas(lock))
 
volatile slock_t g_lock;
 
int s_lock(volatile slock_t *lock)
{
	int i = 0;
 
	while (SPIN(lock)) {
		++i;
	}
 
	return i; 
}
 
void *thread_func(void *args)
{
	while ((cond = sum < max)) {
		s_lock(&g_lock);
		++sum;
		S_UNLOCK(&g_lock);
	}
	
	return NULL;
}
 
int main(void)
{
	pthread_t pids[THREAD_NUM];
	int i, ret;
	void *val;
	double start, end;
 
	S_INIT_LOCK(&g_lock);
 
	for (i = 0; i < THREAD_NUM; ++i) {
		ret = pthread_create(&pids[i], NULL, thread_func, NULL); 
	}
 
	for (i = 0; i < THREAD_NUM; ++i) {
		pthread_join(pids[i], &val);
	}
 
	printf("final sum: %d\n", sum);
	return 0;
}

 

参开资料

1. 使用gcc内置CAS函数实现spinlock

标签:__,gcc,CAS,lock,ptr,int,slock,memorder,spinlock
From: https://www.cnblogs.com/sunbines/p/17697785.html

相关文章

  • mysql case when
    当使用MySQL进行查询时,可以使用CASE表达式来根据条件对结果进行分支处理。CASE表达式在SELECT语句中非常有用,可以根据不同的条件返回不同的值。在本文中,我们将介绍如何使用CASE表达式进行条件分支查询。假设我们有一个名为 transactions 的表,其中包含以下字段:tx_id、t......
  • java.lang.ClassCastException: java.sql.Timestamp cannot be cast to java.lang.Str
    这个问题来自于想把从数据库查询的数据转化为字符串,方便后面做时间比较,显示格式转化错误 sql改造部分 as的左边为我的sql语句语法使用如下DATE_FORMAT((sql语句),'%Y-%m-%d%H:%i:%s')如果是涉及时间的计算,可以考虑如下方式BigDecimala=(BigDecimal)sprint......
  • CtsKeystoreTestCases 测试--和keybox相关的几条用例
    AttestationPerformanceTest测试方式:adbshellaminstrument-r-eclassandroid.keystore.cts.AttestationPerformanceTest-wandroid.keystore.cts/androidx.test.runner.AndroidJUnitRunner需要预置keymasterkey,同时设备需处于locked状态。两个fail项:Therewere2fai......
  • shell脚本嵌套和case语句
    forvarin{list}dodoneforvarinvar1var2var3dodonefor((expr1;expr2;expr3))dodoneforvardodoneuntilexpr[](())dodonewhileexpr[](())dodone随机数:bash中默认有一个变量RANDOM 范围0~32767set|grepRANDOMecho$RANDOM产生0~1之间的随机数echo$[$RANDOM%2]产生......
  • swift switch case 的复杂用法
    Swift中的 switch 语句非常灵活,可以用于处理各种复杂的条件。下面是一些 switch 语句的复杂用法:匹配值和范围:你可以使用 case 子句来匹配特定的值,也可以匹配一个值范围。例如:swiftletnumber=3switchnumber{case1:print("Numberis1")case2,3,4:prin......
  • 系统测试AC5. AC6. IAR和GCC调试效果,MDK AC6不开优化调试乱跳,甚至倒序执行
    首先感谢大家对上一个视频的点评回复,非常有意义的讨论,这次AC6的表现更新惊呆,不开优化都可以乱跳。【实验目的】同样的程序代码,目的是测试C环境的调试现象。【实验版本】IAR版本  :9.3xMDK版本:5.3x,含AC5和AC6EmbeddedStudio:使用GCC,版本V7.1X【视频展示】https://www......
  • gcc安装实战归纳
     安装gcc遇到如下问题:意思就是你的ubuntu版本太高了,但是你要安装的软件版本太低了,所以说嘛!你就得换个强一点的安装器 推荐                 【不推荐使用】aptitude[这玩意儿慎用!可能会导致重装系统]默认的Ubuntu软件源包含了一个软件包组,名称为"build-es......
  • linux gcc rpath
    linux下程序运行时如果想要到指定路径下查找依赖库,除了使用LD_LIBRARY_PATH,还可以使用编译选项rpath:g++-Wl,-rpath='$ORIGIN/libs'-omainmain.cpp-L.-lmylib那么只要把libmylib.so放到libs目录下,main即可正常执行。如果是在QT中,则改为:QMAKE_LFLAGS+="-Wl,-rpath='\$......
  • gcc 常见编译参数
    -c只激活预处理,编译,和汇编-S只激活预处理和编译-E只激活预处理-C在预处理的时候,不删除注释信息-g只是编译器,产生调试信息。-o制定目标名称-w不生成任何警告信息。-M生成文件关联的信息。......
  • 执行python脚本报错:case by sslerror(sslcertVerificationerror(1,ssl:vertificate_ve
    【现象】  使用python编写了一个请求,报错ssl证书过期问题【解决办法】   requests.packages.urllib3.disable_warnings()  r=requests.post(service_url,data=payload,headers=self.headers,verify=False)参考链接:https://www.cnblogs.com/sea-stream/p/14......