Skip to content

Commit 8be5e6f

Browse files
committed
Change Atlas.FallbackStack to ThreadLocal<T>
1 parent aaede13 commit 8be5e6f

1 file changed

Lines changed: 21 additions & 8 deletions

File tree

Celeste.Mod.mm/Patches/Monocle/Atlas.cs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using System;
1010
using System.Collections.Generic;
1111
using System.IO;
12+
using System.Threading;
1213
using System.Xml;
1314
using Logger = Celeste.Mod.Logger;
1415

@@ -21,9 +22,9 @@ class patch_Atlas : Atlas {
2122
/// The internal string-MTexture dictionary.
2223
/// </summary>
2324
public Dictionary<string, MTexture> Textures => textures;
24-
private Dictionary<string, string> links = new Dictionary<string, string>();
25+
private Dictionary<string, string> links;
2526
private Dictionary<string, List<MTexture>> orderedTexturesCache;
26-
private Stack<MTexture> FallbackStack;
27+
private ThreadLocal<Stack<MTexture>> FallbackStack;
2728

2829
public MTexture DefaultFallback;
2930

@@ -33,6 +34,15 @@ class patch_Atlas : Atlas {
3334
public string[] DataPaths;
3435
public AtlasDataFormat? DataFormat;
3536

37+
public extern void orig_ctor();
38+
39+
[MonoModConstructor]
40+
public void ctor() {
41+
links = new Dictionary<string, string>();
42+
FallbackStack = new(() => new());
43+
orig_ctor();
44+
}
45+
3646
[MonoModReplace]
3747
private static void ReadAtlasData(Atlas _atlas, string path, AtlasDataFormat format) {
3848
patch_Atlas atlas = (patch_Atlas) _atlas;
@@ -329,23 +339,26 @@ public void ResetCaches() {
329339
}
330340

331341
public MTexture GetFallback() {
332-
if (FallbackStack != null && FallbackStack.Count > 0)
333-
return FallbackStack.Peek();
342+
if (FallbackStack.IsValueCreated) {
343+
Stack<MTexture> stack = FallbackStack.Value;
344+
if (stack.Count > 0)
345+
return stack.Peek();
346+
}
334347

348+
// we may encounter concurrent issue here but it's safe
349+
// since the worst result is making multiple lookups
335350
if (DefaultFallback != null || textures.TryGetValue("__fallback", out DefaultFallback))
336351
return DefaultFallback;
337352

338353
return null;
339354
}
340355

341356
public void PushFallback(MTexture fallback) {
342-
if (FallbackStack == null)
343-
FallbackStack = new Stack<MTexture>();
344-
FallbackStack.Push(fallback);
357+
FallbackStack.Value.Push(fallback);
345358
}
346359

347360
public MTexture PopFallback() {
348-
return FallbackStack.Pop();
361+
return FallbackStack.Value.Pop();
349362
}
350363

351364
/// <summary>

0 commit comments

Comments
 (0)