Don't use ThreadStatic in Helpers

This commit is contained in:
Garry Newman 2020-05-07 11:47:46 +01:00
parent 04d1c86954
commit b813ee7a17

View File

@ -9,37 +9,35 @@ namespace Steamworks
{ {
public const int MemoryBufferSize = 1024 * 32; public const int MemoryBufferSize = 1024 * 32;
[ThreadStatic] private static IntPtr[] MemoryPool; private static IntPtr[] MemoryPool = new IntPtr[]
[ThreadStatic] private static int MemoryPoolIndex; {
Marshal.AllocHGlobal( MemoryBufferSize ),
Marshal.AllocHGlobal( MemoryBufferSize ),
Marshal.AllocHGlobal( MemoryBufferSize ),
Marshal.AllocHGlobal( MemoryBufferSize )
};
private static int MemoryPoolIndex;
public static unsafe IntPtr TakeMemory() public static unsafe IntPtr TakeMemory()
{ {
if ( MemoryPool == null ) lock ( MemoryPool )
{ {
// MemoryPoolIndex++;
// The pool has 4 items. This should be safe because we shouldn't really
// ever be using more than 2 memory pools
//
MemoryPool = new IntPtr[4];
for ( int i = 0; i < MemoryPool.Length; i++ ) if ( MemoryPoolIndex >= MemoryPool.Length )
MemoryPool[i] = Marshal.AllocHGlobal( MemoryBufferSize ); MemoryPoolIndex = 0;
var take = MemoryPool[MemoryPoolIndex];
((byte*)take)[0] = 0;
return take;
} }
MemoryPoolIndex++;
if ( MemoryPoolIndex >= MemoryPool.Length )
MemoryPoolIndex = 0;
var take = MemoryPool[MemoryPoolIndex];
((byte*)take)[0] = 0;
return take;
} }
[ThreadStatic] private static byte[][] BufferPool; private static byte[][] BufferPool = new byte[4][];
[ThreadStatic] private static int BufferPoolIndex; private static int BufferPoolIndex;
/// <summary> /// <summary>
/// Returns a buffer. This will get returned and reused later on. /// Returns a buffer. This will get returned and reused later on.
@ -47,27 +45,23 @@ namespace Steamworks
/// </summary> /// </summary>
public static byte[] TakeBuffer( int minSize ) public static byte[] TakeBuffer( int minSize )
{ {
if ( BufferPool == null ) lock ( BufferPool )
{ {
// BufferPoolIndex++;
// The pool has 4 items.
//
BufferPool = new byte[4][];
for ( int i = 0; i < BufferPool.Length; i++ ) if ( BufferPoolIndex >= BufferPool.Length )
BufferPool[i] = new byte[ 1024 * 128 ]; BufferPoolIndex = 0;
if ( BufferPool[BufferPoolIndex] == null )
BufferPool[BufferPoolIndex] = new byte[1024 * 256];
if ( BufferPool[BufferPoolIndex].Length < minSize )
{
BufferPool[BufferPoolIndex] = new byte[minSize + 1024];
}
return BufferPool[BufferPoolIndex];
} }
BufferPoolIndex++;
if ( BufferPoolIndex >= BufferPool.Length )
BufferPoolIndex = 0;
if ( BufferPool[BufferPoolIndex].Length < minSize )
{
BufferPool[BufferPoolIndex] = new byte[minSize + 1024];
}
return BufferPool[BufferPoolIndex];
} }
internal unsafe static string MemoryToString( IntPtr ptr ) internal unsafe static string MemoryToString( IntPtr ptr )