Skip to content

Commit 863a684

Browse files
committed
wait for the increments to finish in a separate thread
1 parent 7247da5 commit 863a684

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

src/embed_tests/Modules.cs

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public void TestEval()
5151
ps.Set("a", 1);
5252
var result = ps.Eval<int>("a + 2");
5353
Assert.AreEqual(3, result);
54-
}
54+
}
5555
}
5656

5757
/// <summary>
@@ -286,7 +286,7 @@ public void TestImportScopeFunction()
286286
public void TestVariables()
287287
{
288288
using (Py.GIL())
289-
{
289+
{
290290
(ps.Variables() as dynamic)["ee"] = new PyInt(200);
291291
var a0 = ps.Get<int>("ee");
292292
Assert.AreEqual(200, a0);
@@ -338,34 +338,49 @@ public void TestThread()
338338
" th_cnt += 1\n"
339339
);
340340
}
341-
int th_cnt = 100;
341+
const int th_cnt = 100;
342+
int locked = 0, unlocked = 0, started = 0;
342343
for (int i = 0; i < th_cnt; i++)
343344
{
344-
System.Threading.Thread th = new System.Threading.Thread(() =>
345+
ThreadPool.QueueUserWorkItem(_ =>
346+
// var th = new System.Threading.Thread(() =>
345347
{
348+
Interlocked.Increment(ref started);
346349
using (Py.GIL())
347350
{
351+
Interlocked.Increment(ref locked);
348352
//ps.GetVariable<dynamic>("update")(); //call the scope function dynamicly
349353
_ps.update();
350354
}
355+
Interlocked.Increment(ref unlocked);
351356
});
352-
th.Start();
357+
// th.Start();
353358
}
354359
//equivalent to Thread.Join, make the main thread join the GIL competition
355-
int cnt = 0;
356-
while (cnt != th_cnt)
360+
int result = 0;
361+
var wait = new Thread(() =>
357362
{
363+
int cnt = 0;
364+
while (cnt != th_cnt)
365+
{
366+
using (Py.GIL())
367+
{
368+
cnt = ps.Get<int>("th_cnt");
369+
}
370+
Thread.Yield();
371+
}
372+
358373
using (Py.GIL())
359374
{
360-
cnt = ps.Get<int>("th_cnt");
375+
result = ps.Get<int>("res");
361376
}
362-
Thread.Yield();
363-
}
364-
using (Py.GIL())
377+
});
378+
wait.Start();
379+
if (!wait.Join(timeout: TimeSpan.FromSeconds(30)))
365380
{
366-
var result = ps.Get<int>("res");
367-
Assert.AreEqual(101 * th_cnt, result);
381+
Assert.Fail($"started: {started} locked: {locked} unlocked: {unlocked}");
368382
}
383+
Assert.AreEqual(101 * th_cnt, result);
369384
}
370385
finally
371386
{

0 commit comments

Comments
 (0)