michael@0: // Copyright (c) 2010 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #include "base/threading/thread_collision_warner.h" michael@0: michael@0: #include "base/logging.h" michael@0: #include "base/threading/platform_thread.h" michael@0: michael@0: namespace base { michael@0: michael@0: void DCheckAsserter::warn() { michael@0: NOTREACHED() << "Thread Collision"; michael@0: } michael@0: michael@0: static subtle::Atomic32 CurrentThread() { michael@0: const PlatformThreadId current_thread_id = PlatformThread::CurrentId(); michael@0: // We need to get the thread id into an atomic data type. This might be a michael@0: // truncating conversion, but any loss-of-information just increases the michael@0: // chance of a fault negative, not a false positive. michael@0: const subtle::Atomic32 atomic_thread_id = michael@0: static_cast(current_thread_id); michael@0: michael@0: return atomic_thread_id; michael@0: } michael@0: michael@0: void ThreadCollisionWarner::EnterSelf() { michael@0: // If the active thread is 0 then I'll write the current thread ID michael@0: // if two or more threads arrive here only one will succeed to michael@0: // write on valid_thread_id_ the current thread ID. michael@0: subtle::Atomic32 current_thread_id = CurrentThread(); michael@0: michael@0: int previous_value = subtle::NoBarrier_CompareAndSwap(&valid_thread_id_, michael@0: 0, michael@0: current_thread_id); michael@0: if (previous_value != 0 && previous_value != current_thread_id) { michael@0: // gotcha! a thread is trying to use the same class and that is michael@0: // not current thread. michael@0: asserter_->warn(); michael@0: } michael@0: michael@0: subtle::NoBarrier_AtomicIncrement(&counter_, 1); michael@0: } michael@0: michael@0: void ThreadCollisionWarner::Enter() { michael@0: subtle::Atomic32 current_thread_id = CurrentThread(); michael@0: michael@0: if (subtle::NoBarrier_CompareAndSwap(&valid_thread_id_, michael@0: 0, michael@0: current_thread_id) != 0) { michael@0: // gotcha! another thread is trying to use the same class. michael@0: asserter_->warn(); michael@0: } michael@0: michael@0: subtle::NoBarrier_AtomicIncrement(&counter_, 1); michael@0: } michael@0: michael@0: void ThreadCollisionWarner::Leave() { michael@0: if (subtle::Barrier_AtomicIncrement(&counter_, -1) == 0) { michael@0: subtle::NoBarrier_Store(&valid_thread_id_, 0); michael@0: } michael@0: } michael@0: michael@0: } // namespace base