前些天写压力测试工具,为了统计方便,需要给每个请求带一个独立的id,且希望这个id是自增的。
单线程实现这个功能没什么难度,但压力测试嘛,都是多线程环境。
难道要为这么个小功能加个互斥锁吗?实在是有点不划算。忽然想起某次在开发代码中看到的一个类似__sync_fetch_and_add这样的函数,能实现原子操作,这样就能解决我的问题。
Google被墙,Sogou+Baidu一通搜,找到了出处:
http://www.alexonlinux.com/multithreaded-simple-data-type-access-and-atomic-variables
列举如下:
type __sync_fetch_and_add (type *ptr, type value);
type __sync_fetch_and_sub (type *ptr, type value);
type __sync_fetch_and_or (type *ptr, type value);
type __sync_fetch_and_and (type *ptr, type value);
type __sync_fetch_and_xor (type *ptr, type value);
type __sync_fetch_and_nand (type *ptr, type value);
就第一个函数来说,能够讲ptr所指的变量增加value,且返回操作之前的值,也就是先fetch在增加,其它几个功能不同,字面上一看就明白。
还有与上面对应的另一批,是先操作,再返回:
type __sync_add_and_fetch (type *ptr, type value);
type __sync_sub_and_fetch (type *ptr, type value);
type __sync_or_and_fetch (type *ptr, type value);
type __sync_and_and_fetch (type *ptr, type value);
type __sync_xor_and_fetch (type *ptr, type value);
type __sync_nand_and_fetch (type *ptr, type value);
合理运用这些函数,能节约自己不少时间呢。