views:

192

answers:

1

Hi,

I'm looking for a way to atomically increment a short, and then return that value. I need to do this both in kernel mode and in user mode, so it's in C, under Linux, on Intel 32bit architecture. Unfortunately, due to speed requirements, a mutex lock isn't going to be a good option.

Is there any other way to do this? At this point, it seems like the only option available is to inline some assembly. If that's the case, could someone point me towards the appropriate instructions?

Thanks!

+5  A: 

GCC supports atomic operations:

gcc atomics

dicroce
In particular, `__sync_add_and_fetch` sounds like what the OP is after.
caf
I found those before, but there are two problems. The first is that my understanding is they won't work with the kernel compiler... I'm not sure why that is, so maybe there's an easy work around. Second, even in userspace, the linker gives me the following error:undefined reference to `__sync_add_and_fetch_2'If someone can point out solutions to either of those problems (or both!) I'd be very appreciative.
Bryan
Just as an update, __sync_add_and_fetch does work in userspace, if you include the -march=pentium flag when compiling (http://stackoverflow.com/questions/130740/link-error-when-compiling-gcc-atomic-operation-in-32-bit-mode), so now I'm just working on getting that working in the kernel module.
Bryan
Another update, I believe this is because the function expects an int, whereas I'm using (and constrained to) a short.
Bryan