chromium中的同步机制
我们可以在base\synchronization中看到chromium实现的同步机制,具体的有condition_variable, Lock,Spin_wait, Waitable_event,这几个比较常见的方式。
Lock
Lock的使用
Lock的实现位于 base\synchronization\Lock*.* 中,在synchronization文件夹中,主要是实现线程同步的操作。而Lock其中的一个作用就是在加入队列前互斥访问队列。
bool IncomingTaskQueue::AddToIncomingQueue(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay,
bool nestable) {
//.......
AutoLock locked(incoming_queue_lock_);
PendingTask pending_task(
from_here, task, CalculateDelayedRuntime(delay), nestable);
//......
return PostPendingTask(&pending_task);
}
// The lock that protects access to the members of this class.
base::Lock incoming_queue_lock_;
当我们访问队列的时候,我们要加锁,这里面所有的实现都位于AutoLock中,其中要操作incoming_queue_lock_,其是一个Lock。
Lock的实现
下面我们来具体的分析Lock的实现。这里Lock是系统相关的,我们只是分析Win中的情况,其中Lock的核心实现位于impl中,Lock本身是作为一种封装。
namespace base {
namespace internal {
LockImpl::LockImpl() {
// The second parameter is the spin count, for short-held locks it avoid the
// contending thread from going to sleep which helps performance greatly.
::InitializeCriticalSectionAndSpinCount(&native_handle_, 2000);
}
LockImpl::~LockImpl() {
::DeleteCriticalSection(&native_handle_);
}
bool LockImpl::Try() {
if (::TryEnterCriticalSection(&native_handle_) != FALSE) {
return true;
}
return false;
}
void LockImpl::Lock() {
::EnterCriticalSection(&native_handle_);
}
void LockImpl::Unlock() {
::LeaveCriticalSection(&native_handle_);
}
} // namespace internal
} // namespace base
看到这里,就比较简单了,所谓了Lock就是我们平时常用的CriticalSection,Lock的封装使得基于域的自动加锁和解锁。
Lock的封装
而AutoLock就更为简单的多,也是基于Lock的封装,便于使用。
class AutoLock {
public:
struct AlreadyAcquired {};
explicit AutoLock(Lock& lock) : lock_(lock) {
lock_.Acquire();
}
AutoLock(Lock& lock, const AlreadyAcquired&) : lock_(