今天try了下folly的small lock 很好

#include <stdint.h>
#include <time.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

namespace detail {
	class Sleeper {
		static const uint32_t kMaxActiveSpin = 4000;

		uint32_t spinCount;

		public:
		Sleeper() : spinCount(0) {}

		void wait() {
			if (spinCount < kMaxActiveSpin) {
				++spinCount;
				asm volatile("pause");
			} else {
				struct timespec ts = { 0, 500000 };
				nanosleep(&ts, NULL);
			}
		}
	};

}


struct MicroSpinLock {
	enum { FREE = 0, LOCKED = 1 };
	
	uint8_t lock_;
	
	bool cas(uint8_t compare, uint8_t newVal) {
		bool out;
		asm volatile("lock; cmpxchgb %2, (%3);"
				"setz %0;"
				: "=r" (out)
				: "a" (compare), 
				"q" (newVal),  
				"r" (&lock_)
				: "memory", "flags");
		return out;
	}
	/* try compare 8bit lock with 64bit lock
	uint64_t lock_;
	bool cas(uint64_t compare, uint64_t newVal) {
		bool out;
		asm volatile("lock; cmpxchgq %2, (%3);"
				"setz %0;"
				: "=r" (out)
				: "a" (compare), 
				"q" (newVal),  
				"r" (&lock_)
				: "memory", "flags");
		return out;
	}
	*/

	void init() {
		lock_ = FREE;
	}

	bool try_lock() {
		return cas(FREE, LOCKED);
	}

	void lock() {
		detail::Sleeper sleeper;
		do {
			while (lock_ != FREE) {
				asm volatile("" : : : "memory");
				sleeper.wait();
			}
		} while (!try_lock());
	}

	void unlock() {
		asm volatile("" : : : "memory");
		lock_ = FREE; // release barrier on x86
	}
};


size_t __attribute__((aligned(64))) g_uCount = 0;
MicroSpinLock __attribute__((aligned(64))) locker;
void* sum(void*)
{
	#ifdef NO_LOCK

	for(int i=0;i<250000;++i)
		g_uCount ++ ;

	#endif	

	#ifdef SMALL_LOCK
        	for(int i=0;i<250000;++i)
	{
		locker.lock();
			g_uCount++;
		locker.unlock();

	}
	#endif

};

int main(void)
{
	locker.init();
	pthread_t* thread = (pthread_t*) malloc(10*sizeof( pthread_t));
        	for(int i=0;i<10;++i){       
                pthread_create(&thread[i],NULL,sum,NULL);
        	}
        	for(int i=0;i<10;++i){       
                pthread_join(thread[i],NULL);
        	}
	free(thread);
        	//printf("g_uCount:%d\n",g_uCount);
		
}

 

以上是实验代码,结果比较满意,不细说了,一个lock只需8个bit,不错,对比了4字节的lock没有明显问题。本博客留给自己和感兴趣的朋友们。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值