1 module rt.sys.windows.osmemory; 2 3 version (Windows): 4 5 import core.sys.windows.winbase : GetCurrentThreadId, VirtualAlloc, VirtualFree; 6 import core.sys.windows.winnt : MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE; 7 8 alias pthread_t = int; 9 10 pthread_t pthread_self() nothrow 11 { 12 return cast(pthread_t) GetCurrentThreadId(); 13 } 14 15 /** 16 * Map memory. 17 */ 18 void *os_mem_map(size_t nbytes) nothrow @nogc 19 { 20 return VirtualAlloc(null, nbytes, MEM_RESERVE | MEM_COMMIT, 21 PAGE_READWRITE); 22 } 23 24 25 /** 26 * Unmap memory allocated with os_mem_map(). 27 * Returns: 28 * 0 success 29 * !=0 failure 30 */ 31 int os_mem_unmap(void *base, size_t nbytes) nothrow @nogc 32 { 33 return cast(int)(VirtualFree(base, 0, MEM_RELEASE) == 0); 34 } 35 36 /** 37 Check for any kind of memory pressure. 38 39 Params: 40 mapped = the amount of memory mapped by the GC in bytes 41 Returns: 42 true if memory is scarce 43 */ 44 // TODO: get virtual mem sizes and current usage from OS 45 // TODO: compare current RSS and avail. physical memory 46 bool isLowOnMem(size_t mapped) nothrow @nogc 47 { 48 import core.sys.windows.winbase : GlobalMemoryStatusEx, MEMORYSTATUSEX; 49 50 MEMORYSTATUSEX stat; 51 stat.dwLength = stat.sizeof; 52 const success = GlobalMemoryStatusEx(&stat) != 0; 53 assert(success, "GlobalMemoryStatusEx() failed"); 54 if (!success) 55 return false; 56 57 // dwMemoryLoad is the 'approximate percentage of physical memory that is in use' 58 // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-memorystatusex 59 const percentPhysicalRAM = stat.ullTotalPhys / 100; 60 return (stat.dwMemoryLoad >= 95 && mapped > percentPhysicalRAM) 61 || (stat.dwMemoryLoad >= 90 && mapped > 10 * percentPhysicalRAM); 62 } 63 64 65 /** 66 Get the size of available physical memory 67 68 Returns: 69 size of installed physical RAM 70 */ 71 ulong os_physical_mem() nothrow @nogc 72 { 73 import core.sys.windows.winbase : GlobalMemoryStatus, MEMORYSTATUS; 74 MEMORYSTATUS stat; 75 GlobalMemoryStatus(&stat); 76 return stat.dwTotalPhys; // limited to 4GB for Win32 77 } 78 79 80 /** 81 Get get the page size of OS 82 83 Returns: 84 OS page size in bytes 85 */ 86 size_t getPageSize() 87 { 88 import core.sys.windows.winbase : GetSystemInfo, SYSTEM_INFO; 89 90 SYSTEM_INFO si; 91 GetSystemInfo(&si); 92 return cast(size_t) si.dwPageSize; 93 }