前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >简单了解C语言内嵌汇编

简单了解C语言内嵌汇编

作者头像
charlieroro
发布2020-03-24 11:40:10
1.3K0
发布2020-03-24 11:40:10
举报
文章被收录于专栏:charlieroro

最近看自旋锁的实现,自选锁的循环查找锁的主要实现类似如下,该实现使用到了内嵌的汇编(摘自sanos内核,源代码有2处实现,一处使用intel汇编,是没有问题的,另一处使用内嵌汇编语法,源代码中为cmpxchgl %2, %0,是错误的,应该是cmpxchgl %0, %2)

内嵌汇编有个固定格式,如下:

代码语言:javascript
复制
asm ( assembler template         /* 汇编语句 */
    : output operands                  /* 输出 */
    : input operands                   /* 输入 */
    : list of clobbered registers     
    );

cmpxchgl的描述如下:

Compares the value in the AL, AX, EAX, or RAX register with the first operand (destination operand). If the twovalues are equal, the second operand (source operand) is loaded into the destination operand. Otherwise, thedestination operand is loaded into the AL, AX, EAX or RAX register. RAX register is available only in 64-bit mode. (* Accumulator = AL, AX, EAX, or RAX depending on whether a byte, word, doubleword, or quadword comparison is being performed *) TEMP ← DEST IF accumulator = TEMP THEN ZF ← 1; DEST ← SRC; ELSE ZF ← 0; accumulator ← TEMP; DEST ← TEMP; FI;

  1. cmpxchgl %0, %2为汇编语句,表示对第3个和第1个入参进行操作,即cmpxchgl *dest,exchange;
  2. "=m" (*dest), "=a" (old)为输出部分,将m内存的内容存到*dest中,将a寄存器内容存到old;
  3. "r" (exchange), "m" (*dest), "a" (comperand)); 为输入部分,将exchange放入r寄存器,将*dest放入m,将comperand放入a寄存器;

使用C语言翻译如下:

代码语言:javascript
复制
int atomic_compare_and_exchange(int *dest, int exchange, int comperand) 
{
    int old = comperand;
    if ( comperand== *dest)
    {
        *dest = exchange;
    }
    else
    {
        old  = *dest;
    }
    return old;
}

参考:http://blog.chinaunix.net/uid-23955580-id-2945814.html

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-02-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档