Suppress data races in blink::Scheduler
[chromium-blink-merge.git] / base / memory / discardable_memory_shmem_allocator.cc
blob8abe4569382e8d66f407aba397f296fbd6e17b62
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/memory/discardable_memory_shmem_allocator.h"
7 #include "base/lazy_instance.h"
8 #include "base/logging.h"
9 #include "base/memory/discardable_shared_memory.h"
11 namespace base {
12 namespace {
14 class DiscardableMemoryShmemChunkImpl : public DiscardableMemoryShmemChunk {
15 public:
16 explicit DiscardableMemoryShmemChunkImpl(
17 scoped_ptr<DiscardableSharedMemory> shared_memory)
18 : shared_memory_(shared_memory.Pass()) {}
20 // Overridden from DiscardableMemoryShmemChunk:
21 bool Lock() override {
22 auto result = shared_memory_->Lock(0, 0);
23 DCHECK_NE(result, DiscardableSharedMemory::PURGED);
24 return result == DiscardableSharedMemory::SUCCESS;
26 void Unlock() override { shared_memory_->Unlock(0, 0); }
27 void* Memory() const override { return shared_memory_->memory(); }
28 bool IsMemoryResident() const override {
29 return shared_memory_->IsMemoryResident();
32 private:
33 scoped_ptr<DiscardableSharedMemory> shared_memory_;
35 DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryShmemChunkImpl);
38 // Default allocator implementation that allocates in-process
39 // DiscardableSharedMemory instances.
40 class DiscardableMemoryShmemAllocatorImpl
41 : public DiscardableMemoryShmemAllocator {
42 public:
43 // Overridden from DiscardableMemoryShmemAllocator:
44 scoped_ptr<DiscardableMemoryShmemChunk>
45 AllocateLockedDiscardableMemory(size_t size) override {
46 scoped_ptr<DiscardableSharedMemory> memory(new DiscardableSharedMemory);
47 if (!memory->CreateAndMap(size))
48 return nullptr;
50 return make_scoped_ptr(new DiscardableMemoryShmemChunkImpl(memory.Pass()));
54 LazyInstance<DiscardableMemoryShmemAllocatorImpl>::Leaky g_default_allocator =
55 LAZY_INSTANCE_INITIALIZER;
57 DiscardableMemoryShmemAllocator* g_allocator = nullptr;
59 } // namespace
61 // static
62 void DiscardableMemoryShmemAllocator::SetInstance(
63 DiscardableMemoryShmemAllocator* allocator) {
64 DCHECK(allocator);
66 // Make sure this function is only called once before the first call
67 // to GetInstance().
68 DCHECK(!g_allocator);
70 g_allocator = allocator;
73 // static
74 DiscardableMemoryShmemAllocator*
75 DiscardableMemoryShmemAllocator::GetInstance() {
76 if (!g_allocator)
77 g_allocator = g_default_allocator.Pointer();
79 return g_allocator;
82 } // namespace base