浏览代码

Merge pull request #1718 from zakki/debugmem-thread

Fix race condition in DebugNew
Sean Taylor 11 年之前
父节点
当前提交
1ecad0e169
共有 1 个文件被更改,包括 10 次插入0 次删除
  1. 10 0
      gameplay/src/DebugNew.cpp

+ 10 - 0
gameplay/src/DebugNew.cpp

@@ -4,6 +4,8 @@
 #include <exception>
 #include <exception>
 #include <cstdio>
 #include <cstdio>
 #include <cstdarg>
 #include <cstdarg>
+#include <thread>
+#include <mutex>
 
 
 #ifdef WIN32
 #ifdef WIN32
 #include <windows.h>
 #include <windows.h>
@@ -31,6 +33,12 @@ struct MemoryAllocationRecord
 MemoryAllocationRecord* __memoryAllocations = 0;
 MemoryAllocationRecord* __memoryAllocations = 0;
 int __memoryAllocationCount = 0;
 int __memoryAllocationCount = 0;
 
 
+static std::mutex& getMemoryAllocationMutex()
+{
+    static std::mutex m;
+    return m;
+}
+
 void* debugAlloc(std::size_t size, const char* file, int line);
 void* debugAlloc(std::size_t size, const char* file, int line);
 void debugFree(void* p);
 void debugFree(void* p);
 
 
@@ -105,6 +113,7 @@ void* debugAlloc(std::size_t size, const char* file, int line)
     // Move memory pointer past record
     // Move memory pointer past record
     mem += sizeof(MemoryAllocationRecord);
     mem += sizeof(MemoryAllocationRecord);
 
 
+    std::lock_guard<std::mutex> lock(getMemoryAllocationMutex());
     rec->address = (unsigned long)mem;
     rec->address = (unsigned long)mem;
     rec->size = (unsigned int)size;
     rec->size = (unsigned int)size;
     rec->file = file;
     rec->file = file;
@@ -194,6 +203,7 @@ void debugFree(void* p)
     }
     }
 
 
     // Link this item out
     // Link this item out
+    std::lock_guard<std::mutex> lock(getMemoryAllocationMutex());
     if (__memoryAllocations == rec)
     if (__memoryAllocations == rec)
         __memoryAllocations = rec->next;
         __memoryAllocations = rec->next;
     if (rec->prev)
     if (rec->prev)