Hello,

I've just begun working with assembly so I'm sorry if this question is simplistic. I would like to implement an atomic add (for incrementing an array pointer). My code looks like this:

int * ptr;
int step;
asm("lock add %1, %2;\n"
    :"=m"(ptr)
    :"m"(ptr),"r"(step)
    :
    );

But I'm getting an error "expecting lockable instruction after 'lock'", which doesn't make sense as I've read that add is a lockable instruction. If I place the lock as a separate instruction before the addition it compiles, but ultimate crashes as it claims it is an "illegal instruction." Perhaps I'm understanding the use of add here incorrectly? I believe it is fetching the value pointed to by 'ptr', adding the 'step', and storing the result to the address referenced by 'ptr'.

If someone could explain what is happening I would appreciate it.

Thanks!

So I figured out the problem. The ptr needs to be dereferenced first. The working code looks like this:

asm("lock add %1, %2;\n"
    :"=m"(*ptr)
    :"m"(*ptr),"r"(step)
    :
    );

Sorry guys, the last answered is still has same output.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.