linux 文件锁的特点

int _lock_fd(int fd) {
	struct flock fl;
	memset(&fl, 0, sizeof(struct flock));

	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;

	if (fcntl(fd, F_SETLKW, &fl) == -1) {
		return -1;
	}

	return 0;
}

int _unlock_fd(int fd) {
	struct flock fl;
	memset(&fl, 0, sizeof(struct flock));

	fl.l_type = F_UNLCK;
	fl.l_whence = SEEK_SET;

	if (fcntl(fd, F_SETLK, &fl) == -1) {
		return -1;
	}

	return 0;
}

这是常用的linux文件锁

特点:(1)速度很快 2.7GHz的cpu上几个微妙就能进入锁

(2)等待特点:跨进程时,会等,如A进程进入锁定,则B进程要等到A进程解锁后才能加锁

(3)同进程内的情况,当A线程锁定,则B线程不会等,而是直接返回锁定失败

因此如果实现类似Windows的Mutex特点,需要再进入文件锁前进入一个进程内的临界区

bool CProcessMutex::Lock() {
	//mutex lock first
	m_mutex.lock();

	long long cur_tid = GetCurrentTid();
	if (cur_tid == m_currentThreadID)
		return true;

	m_currentThreadID = cur_tid;
	bool bLockSem = LockFile();
	if (!bLockSem) {
		m_currentThreadID = 0;
		m_mutex.unlock();
		return false;
	}

	return true;
}

bool CProcessMutex::UnLock() {
	if (UnLockFile()) {
		m_currentThreadID = 0;
		m_mutex.unlock();
		return true;
	}
	return false;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值