Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(gameengine): add a fork-join job pool

Olcay Seygan21e96a65c2dc
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/JobSystem.h b/GeneralsMD/Code/GameEngine/Include/Common/JobSystem.h
new file mode 100644
index 000000000..e0c42fd38
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Include/Common/JobSystem.h
@@ -0,0 +1,108 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: JobSystem.h //////////////////////////////////////////////////////////////////////////////
+// Desc: THREADING-ROADMAP.md 3.1 - a fork-join pool, and nothing else.
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+#pragma once
+
+#ifndef __JOBSYSTEM_H__
+#define __JOBSYSTEM_H__
+
+#include "Lib/BaseType.h"
+
+/**
+ * A deliberately minimal fork-join pool. One entry point, no task dependencies, no work
+ * stealing, no futures - because the only workloads on the roadmap are pure functions over an
+ * array (THREADING-ROADMAP.md section 3), and everything past fork-join is code nobody has a
+ * use for yet.
+ *
+ * Three rules the callers have to keep, all of them from section 1 of that document:
+ *
+ * 1. **A job must not allocate.** Every MemoryPool in the game shares one critical section
+ * (GameMemory.cpp), so one newInstance per work item turns parallel work back into a queue.
+ * Size and allocate on the calling thread before the fork; workers only write into memory
+ * that already exists. Violations are counted - workerAllocationCount() - rather than left
+ * to be found later as a mystery perf regression.
+ *
+ * 2. **A job must not touch simulation state.** The lockstep sequence is the simulation; a
+ * draw from GameLogicRandomValue or a write an Object reads back desyncs a multiplayer game
+ * hours later with no reproducible case.
+ *
+ * 3. **Output order must not depend on scheduling.** Write into a pre-sized array indexed by
+ * item, or concatenate per-job lists afterwards in item order. Never append to one shared
+ * list from inside a job.
+ *
+ * The FPU control word is per-thread and resets to the CRT default on every new thread, so each
+ * worker calls setFPMode() once on entry (section 1.3).
+ */
+namespace JobSystem
+{
+
+ /** The body of one work item. `index` is the item, `context` is whatever was handed to
+ * parallel_for. A plain function pointer, not a std::function: a std::function that does not
+ * fit its small-object buffer allocates, and rule 1 above says jobs do not allocate. */
+ typedef void (*JobFunc)( Int index, void *context );
+
+ /** Start the pool. `workers` is the number of *extra* threads, since the calling thread works
+ * too. 0 means no pool at all - parallel_for runs inline. A negative value, the default,
+ * asks the command line: `-jobthreads <n>` if it is there, otherwise one fewer than the
+ * machine has processors.
+ *
+ * `-jobthreads 0` is the point of that switch: it is how a threading change is measured
+ * against its own single-threaded baseline in the same binary, on the same machine, without
+ * a rebuild in between.
+ *
+ * Calling this twice without a shutdown() in between does nothing the second time. */
+ void init( Int workers = -1 );
+
+ /** Stop the pool and join every worker. Safe to call without an init(), and safe to call
+ * while another shutdown is not in flight; there is no work in flight by construction,
+ * because parallel_for does not return until its fork has joined. */
+ void shutdown( void );
+
+ /** Extra threads in the pool. 0 means parallel_for runs everything inline, which is a
+ * supported configuration and the one a single-core machine gets. */
+ Int workerCount( void );
+
+ /** Run fn(0..count-1, context) across the pool and return when every item is done.
+ *
+ * `granularity` is the smallest number of consecutive items a thread claims at once. It is
+ * not a hint that can be ignored: it is how a caller says "an item is cheap, do not pay an
+ * interlocked claim for each one". Anything below 1 is read as 1.
+ *
+ * With count <= granularity, or with no workers, this runs the whole range inline on the
+ * calling thread - the same code path, so a single-threaded machine is a supported build
+ * and not an untested one. */
+ void parallel_for( Int count, Int granularity, JobFunc fn, void *context );
+
+ /** TRUE on a pool worker, FALSE on the thread that called parallel_for (and everywhere else). */
+ Bool isWorkerThread( void );
+
+ /** How many times a pool worker has allocated from a MemoryPool since the process started.
+ * Rule 1 says this is zero. It is a count rather than an assert because the Debug config
+ * cannot link this tree standalone, so a _DEBUG-only check would never actually run. */
+ Int workerAllocationCount( void );
+
+ /** Called by the allocator, not by game code. */
+ void noteWorkerAllocation( void );
+
+} // namespace JobSystem
+
+#endif // __JOBSYSTEM_H__
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp
index a97cc2769..7b6ba7122 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp
@@ -52,6 +52,7 @@
#include "Common/Errors.h"
#include "Common/GlobalData.h"
#include "Common/PerfTimer.h"
+#include "Common/JobSystem.h"
#ifdef MEMORYPOOL_DEBUG
#include "GameClient/ClientRandomValue.h"
#endif
@@ -1629,6 +1630,17 @@ Int MemoryPool::freeBlob(MemoryPoolBlob* blob)
*/
void* MemoryPool::allocateBlockDoNotZeroImplementation(DECLARE_LITERALSTRING_ARG1)
{
+ /* THREADING-ROADMAP.md 1.1 and 3.1. Every pool in the game shares the one critical section
+ below, so an allocation inside a job does not crash - it serializes the whole fork against
+ every other thread, and the parallel work turns back into a queue plus lock overhead. That
+ failure mode is invisible: the output is correct and the frame is slower. So it is counted
+ here, where it happens, and reported at the end of a run.
+
+ A count and not a DEBUG_ASSERTCRASH because this tree's Debug config cannot link standalone
+ (CLAUDE.md, Hard constraints), so a _DEBUG-only check would never once run. */
+ if (JobSystem::isWorkerThread())
+ JobSystem::noteWorkerAllocation();
+
ScopedCriticalSection scopedCriticalSection(TheMemoryPoolCriticalSection);
if (m_firstBlobWithFreeBlocks != NULL && !m_firstBlobWithFreeBlocks->hasAnyFreeBlocks())
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/JobSystem.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/JobSystem.cpp
new file mode 100644
index 000000000..d5a10e43f
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/JobSystem.cpp
@@ -0,0 +1,257 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: JobSystem.cpp ////////////////////////////////////////////////////////////////////////////
+// Desc: THREADING-ROADMAP.md 3.1 - a fork-join pool, and nothing else.
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+#include "PreRTS.h"
+#include "Common/JobSystem.h"
+#include "Common/EarlyCommandLine.h"
+#include "GameLogic/FPUControl.h"
+
+namespace
+{
+
+ enum { MAX_WORKERS = 31 }; // one interlocked counter's worth; nothing here scales past it
+
+ HANDLE s_threads[ MAX_WORKERS ] = { 0 };
+ Int s_numWorkers = 0;
+ Bool s_running = FALSE;
+
+ HANDLE s_workReady = NULL; // released once per worker at each fork
+ HANDLE s_allDone = NULL; // auto-reset; set by the last worker to finish
+ volatile LONG s_quitting = 0;
+
+ // The job in flight. Written by the forking thread before the semaphore is released and read
+ // by the workers after they wake on it, which is the pairing that publishes them.
+ JobSystem::JobFunc s_fn = NULL;
+ void *s_context = NULL;
+ volatile LONG s_nextIndex = 0;
+ LONG s_count = 0;
+ LONG s_grain = 1;
+ volatile LONG s_workersBusy = 0;
+
+ // Per-thread, so the allocator can tell whose hand is in the pool without a lock of its own.
+ __declspec(thread) Bool s_isWorker = FALSE;
+ volatile LONG s_workerAllocations = 0;
+
+ /** Claim chunks of the current job until there are none left. Every thread in the fork runs
+ * this, the forking one included - a pool of N-1 workers plus the caller is N threads of
+ * work, and the caller blocking while the workers run would waste the best one of them. */
+ void runChunks( void )
+ {
+ for( ;; )
+ {
+ const LONG start = InterlockedExchangeAdd( (LONG *)&s_nextIndex, s_grain );
+ if( start >= s_count )
+ break;
+
+ LONG end = start + s_grain;
+ if( end > s_count )
+ end = s_count;
+
+ for( LONG i = start; i < end; ++i )
+ s_fn( (Int)i, s_context );
+ }
+ }
+
+ DWORD WINAPI workerMain( LPVOID )
+ {
+ s_isWorker = TRUE;
+
+ /* The FPU control word is per-thread and a new thread starts on the CRT default, not on
+ what setFPMode() left on the main thread. A job that computes a float with a different
+ precision or rounding mode than the rest of the game is the kind of bug that shows up as
+ a rare visual difference and never as a crash, so this is not optional even for work
+ that never touches the simulation. */
+ setFPMode();
+
+ for( ;; )
+ {
+ WaitForSingleObject( s_workReady, INFINITE );
+ if( s_quitting )
+ break;
+
+ runChunks();
+
+ if( InterlockedDecrement( (LONG *)&s_workersBusy ) == 0 )
+ SetEvent( s_allDone );
+ }
+ return 0;
+ }
+
+} // anonymous namespace
+
+//-------------------------------------------------------------------------------------------------
+void JobSystem::init( Int workers )
+{
+ if( s_running )
+ return;
+
+ if( workers < 0 )
+ {
+ /* -jobthreads <n>, read here rather than from CommandLine.cpp's table because the pool is
+ started before that table runs and because 0 has to be reachable - which is the whole
+ point: it is the single-threaded baseline to measure a threading change against. */
+ char value[ 32 ];
+ if( findEarlyCommandLineValue( L"-jobthreads", value, sizeof(value) ) )
+ {
+ workers = atoi( value );
+ }
+ else
+ {
+ SYSTEM_INFO si;
+ ::GetSystemInfo( &si );
+ // The forking thread works too, so the pool wants one fewer than the machine has.
+ workers = (Int)si.dwNumberOfProcessors - 1;
+ }
+ }
+ if( workers > MAX_WORKERS )
+ workers = MAX_WORKERS;
+ if( workers < 0 )
+ workers = 0;
+
+ s_quitting = 0;
+ s_numWorkers = 0;
+
+ if( workers > 0 )
+ {
+ s_workReady = ::CreateSemaphore( NULL, 0, MAX_WORKERS, NULL );
+ s_allDone = ::CreateEvent( NULL, FALSE, FALSE, NULL );
+ if( s_workReady == NULL || s_allDone == NULL )
+ {
+ // No pool is a supported configuration - parallel_for runs inline - so a failure here
+ // costs speed, never correctness.
+ DEBUG_LOG(("JobSystem: could not create sync objects, running single threaded\n"));
+ if( s_workReady ) { ::CloseHandle( s_workReady ); s_workReady = NULL; }
+ if( s_allDone ) { ::CloseHandle( s_allDone ); s_allDone = NULL; }
+ workers = 0;
+ }
+ }
+
+ for( Int i = 0; i < workers; ++i )
+ {
+ DWORD id = 0;
+ s_threads[ i ] = ::CreateThread( NULL, 0, workerMain, NULL, 0, &id );
+ if( s_threads[ i ] == NULL )
+ break; // take what we got; the pool is allowed to be smaller than asked for
+ ++s_numWorkers;
+ }
+
+ s_running = TRUE;
+ DEBUG_LOG(("JobSystem: %d worker threads\n", s_numWorkers));
+}
+
+//-------------------------------------------------------------------------------------------------
+void JobSystem::shutdown( void )
+{
+ if( !s_running )
+ return;
+
+ /* There is never work in flight here: parallel_for does not return until its fork has joined,
+ so by the time anything can call this every worker is parked on the semaphore. */
+ s_quitting = 1;
+ if( s_workReady && s_numWorkers > 0 )
+ ::ReleaseSemaphore( s_workReady, s_numWorkers, NULL );
+
+ for( Int i = 0; i < s_numWorkers; ++i )
+ {
+ if( s_threads[ i ] )
+ {
+ /* Bounded, not INFINITE. This runs on the way out of the process and a worker that
+ somehow never wakes must not be able to hang the exit; the handle leaks instead,
+ which costs nothing at that point. */
+ if( ::WaitForSingleObject( s_threads[ i ], 5000 ) == WAIT_OBJECT_0 )
+ ::CloseHandle( s_threads[ i ] );
+ else
+ DEBUG_LOG(("JobSystem: worker %d did not exit, leaking its handle\n", i));
+ s_threads[ i ] = NULL;
+ }
+ }
+ s_numWorkers = 0;
+
+ if( s_workReady ) { ::CloseHandle( s_workReady ); s_workReady = NULL; }
+ if( s_allDone ) { ::CloseHandle( s_allDone ); s_allDone = NULL; }
+ s_running = FALSE;
+}
+
+//-------------------------------------------------------------------------------------------------
+Int JobSystem::workerCount( void )
+{
+ return s_numWorkers;
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool JobSystem::isWorkerThread( void )
+{
+ return s_isWorker;
+}
+
+//-------------------------------------------------------------------------------------------------
+Int JobSystem::workerAllocationCount( void )
+{
+ return (Int)s_workerAllocations;
+}
+
+//-------------------------------------------------------------------------------------------------
+void JobSystem::noteWorkerAllocation( void )
+{
+ InterlockedIncrement( (LONG *)&s_workerAllocations );
+}
+
+//-------------------------------------------------------------------------------------------------
+void JobSystem::parallel_for( Int count, Int granularity, JobFunc fn, void *context )
+{
+ if( count <= 0 || fn == NULL )
+ return;
+
+ if( granularity < 1 )
+ granularity = 1;
+
+ /* Inline when there is nobody to hand work to, or when the whole range is one chunk anyway.
+ Same code path as the parallel case would take for a single chunk, so the single-threaded
+ machine is running tested code rather than a second implementation. */
+ if( s_numWorkers <= 0 || count <= granularity )
+ {
+ for( Int i = 0; i < count; ++i )
+ fn( i, context );
+ return;
+ }
+
+ DEBUG_ASSERTCRASH( !s_isWorker, ("JobSystem::parallel_for from inside a job - this pool does not nest") );
+
+ s_fn = fn;
+ s_context = context;
+ s_count = (LONG)count;
+ s_grain = (LONG)granularity;
+ s_nextIndex = 0;
+ s_workersBusy = s_numWorkers;
+
+ ::ReleaseSemaphore( s_workReady, s_numWorkers, NULL );
+
+ runChunks(); // the forking thread is a worker too
+
+ /* Wait for the workers, not for the work: the chunks can all be claimed by this thread while a
+ worker is still on its way out of WaitForSingleObject, and returning then would let the
+ caller reuse the output buffers under it. */
+ ::WaitForSingleObject( s_allDone, INFINITE );
+
+ s_fn = NULL;
+ s_context = NULL;
+}
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index dea8869f6..1372b196b 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -94,6 +94,8 @@
#include "GameLogic/Module/QueueProductionExitUpdate.h"
#include "GameLogic/Module/SupplyCenterProductionExitUpdate.h"
#include "WWMath/matrix3d.h"
+#include "Common/JobSystem.h"
+#include "Common/CriticalSection.h"
#include "GameClient/Drawable.h"
#include "Common/BuildAssistant.h"
#include "GameLogic/Object.h"
@@ -7231,3 +7233,233 @@ TEST(a_mirrored_image_is_the_same_piece_of_texture_the_other_way_round)
mirrored->deleteInstance();
source->deleteInstance();
}
+
+//-------------------------------------------------------------------------------------------------
+// THREADING-ROADMAP.md 3.1 - the fork-join pool.
+//
+// Everything the roadmap puts on top of this pool is a pure function over an array, so the pool
+// itself is the only place a data race can be introduced by construction rather than by review -
+// and there is no TSan on MSVC/Win32 x86 (section 7). These tests are therefore about the two
+// promises the callers rely on and nothing else: every item runs exactly once, and a worker
+// computes floats the way the rest of the game does.
+//-------------------------------------------------------------------------------------------------
+
+enum { JOB_TEST_MAX = 4096 };
+static Int s_jobVisits[ JOB_TEST_MAX ];
+static UnsignedInt s_jobFPMode[ JOB_TEST_MAX ];
+static Int s_jobWorkerFlag[ JOB_TEST_MAX ];
+static volatile LONG s_jobWorkerSeen = 0;
+static volatile LONG s_jobWaitedOnce = 0;
+
+/* The forking thread works the queue too, and a job body that does nothing at all is finished long
+ before a worker is out of WaitForSingleObject - so a test that wants to observe a worker has to
+ hold the first item until one turns up. One bounded wait per fork, and none at all once a
+ worker has been seen, so this costs nothing when the pool is behaving. */
+static void jobTestWaitForAWorker( void )
+{
+ if( JobSystem::isWorkerThread() )
+ {
+ InterlockedExchange( (LONG *)&s_jobWorkerSeen, 1 );
+ return;
+ }
+ if( s_jobWorkerSeen || InterlockedExchange( (LONG *)&s_jobWaitedOnce, 1 ) != 0 )
+ return;
+
+ const DWORD deadline = ::GetTickCount() + 500;
+ while( !s_jobWorkerSeen && ::GetTickCount() < deadline )
+ ::Sleep( 0 );
+}
+
+static void jobTestCount( Int index, void * )
+{
+ // Each item owns its own slot, so this needs no lock and no atomic - which is the shape every
+ // job on the roadmap has to have.
+ ++s_jobVisits[ index ];
+}
+
+static void jobTestRecordFPU( Int index, void * )
+{
+ jobTestWaitForAWorker();
+ s_jobFPMode[ index ] = getFPMode();
+ s_jobWorkerFlag[ index ] = JobSystem::isWorkerThread() ? 1 : 0;
+}
+
+static void jobTestAllocate( Int index, void * )
+{
+ // Deliberately breaks the no-allocation rule, to prove the counter that watches for it is not
+ // simply stuck at zero.
+ jobTestWaitForAWorker();
+ Image *img = newInstance( Image );
+ s_jobVisits[ index ] = 1;
+ img->deleteInstance();
+}
+
+static void resetJobVisits( void )
+{
+ s_jobWorkerSeen = 0;
+ s_jobWaitedOnce = 0;
+ for( Int i = 0; i < JOB_TEST_MAX; ++i )
+ {
+ s_jobVisits[ i ] = 0;
+ s_jobFPMode[ i ] = 0;
+ s_jobWorkerFlag[ i ] = 0;
+ }
+}
+
+/* The one thing every caller assumes: the range is covered, once, and parallel_for does not come
+ back before that is true. Run over a spread of counts and granularities, including the ones
+ that make the split uneven and the ones that collapse it to a single chunk. */
+TEST(parallel_for_runs_every_item_exactly_once)
+{
+ static const Int counts[] = { 0, 1, 2, 3, 7, 8, 63, 64, 65, 1000, 4096 };
+ static const Int grains[] = { 1, 2, 3, 16, 4096 };
+
+ JobSystem::shutdown();
+ JobSystem::init( 4 );
+ CHECK_EQ( 4, JobSystem::workerCount() );
+
+ const Int numCounts = (Int)(sizeof(counts)/sizeof(counts[0]));
+ const Int numGrains = (Int)(sizeof(grains)/sizeof(grains[0]));
+ for( Int c = 0; c < numCounts; ++c )
+ {
+ for( Int g = 0; g < numGrains; ++g )
+ {
+ resetJobVisits();
+ JobSystem::parallel_for( counts[c], grains[g], jobTestCount, NULL );
+
+ Int seen = 0;
+ for( Int i = 0; i < JOB_TEST_MAX; ++i )
+ {
+ if( i < counts[c] )
+ seen += (s_jobVisits[ i ] == 1) ? 1 : 0;
+ else
+ CHECK_EQ( 0, s_jobVisits[ i ] ); // never runs past the end of the range
+ }
+ CHECK_EQ( counts[c], seen );
+ }
+ }
+
+ // A granularity below 1 is a caller mistake, not a division by zero.
+ resetJobVisits();
+ JobSystem::parallel_for( 10, 0, jobTestCount, NULL );
+ for( Int i = 0; i < 10; ++i )
+ CHECK_EQ( 1, s_jobVisits[ i ] );
+
+ JobSystem::shutdown();
+}
+
+/* A machine with one core, or a build that asks for no pool, has to run the same code rather than
+ a second single-threaded implementation nobody tests. */
+TEST(parallel_for_with_no_workers_still_runs_everything)
+{
+ JobSystem::shutdown();
+ JobSystem::init( 0 );
+ CHECK_EQ( 0, JobSystem::workerCount() );
+
+ resetJobVisits();
+ JobSystem::parallel_for( 100, 4, jobTestCount, NULL );
+ for( Int i = 0; i < 100; ++i )
+ CHECK_EQ( 1, s_jobVisits[ i ] );
+
+ // and on the calling thread, so nothing inside a job may believe it is on a worker
+ resetJobVisits();
+ JobSystem::parallel_for( 8, 1, jobTestRecordFPU, NULL );
+ for( Int i = 0; i < 8; ++i )
+ CHECK_EQ( 0, s_jobWorkerFlag[ i ] );
+
+ JobSystem::shutdown();
+}
+
+/* THREADING-ROADMAP.md 1.3. The FPU control word is per-thread and a new thread starts on the
+ CRT default, not on what setFPMode() left on the main thread. A worker that computes floats at
+ a different precision or rounding mode produces results that differ from the main thread's for
+ no visible reason - the kind of bug that never crashes and never reproduces. */
+TEST(a_job_computes_floats_the_way_the_game_does)
+{
+ setFPMode();
+
+ JobSystem::shutdown();
+ JobSystem::init( 4 );
+
+ resetJobVisits();
+ // One item per chunk over a range far bigger than the pool, so every worker takes some.
+ JobSystem::parallel_for( 512, 1, jobTestRecordFPU, NULL );
+
+ Int ranOnAWorker = 0;
+ for( Int i = 0; i < 512; ++i )
+ {
+ CHECK_EQ( expectedFPMode(), s_jobFPMode[ i ] );
+ ranOnAWorker += s_jobWorkerFlag[ i ];
+ }
+ // ...and the check above was not vacuous because the main thread ran all of it
+ CHECK( ranOnAWorker > 0 );
+
+ // the fork left the calling thread's own mode alone
+ CHECK_EQ( expectedFPMode(), getFPMode() );
+
+ JobSystem::shutdown();
+}
+
+/* THREADING-ROADMAP.md 1.1: every MemoryPool in the game shares one critical section, so an
+ allocation inside a job does not crash - it quietly serializes the fork. The counter is the
+ only thing that can see that happen, so it has to be shown to move. */
+TEST(an_allocation_inside_a_job_is_counted)
+{
+ JobSystem::shutdown();
+ JobSystem::init( 4 );
+
+ const Int before = JobSystem::workerAllocationCount();
+
+ resetJobVisits();
+ JobSystem::parallel_for( 256, 1, jobTestCount, NULL );
+ CHECK_EQ( before, JobSystem::workerAllocationCount() ); // a well-behaved job costs nothing
+
+ /* WinMain installs this and nothing else does, so in a test binary the pools are unguarded -
+ and the job below allocates from several threads at once on purpose. Without it this test
+ corrupts a pool and hangs, which is itself the point of section 1.1: the allocator is safe
+ to call from a worker only because that one global lock is there. */
+ CriticalSection poolLock;
+ TheMemoryPoolCriticalSection = &poolLock;
+
+ resetJobVisits();
+ JobSystem::parallel_for( 256, 1, jobTestAllocate, NULL );
+
+ TheMemoryPoolCriticalSection = NULL;
+
+ CHECK( JobSystem::workerAllocationCount() > before );
+
+ JobSystem::shutdown();
+}
+
+/* The pool is torn down inside ~GameEngine, on the way out of a process that may be quitting from
+ anywhere. It has to survive being stopped without ever being started, being stopped twice, and
+ being started again afterwards - none of which may hang. */
+TEST(the_pool_survives_being_started_and_stopped_repeatedly)
+{
+ JobSystem::shutdown();
+ JobSystem::shutdown(); // no pool: nothing to do, and no wait to hang on
+ CHECK_EQ( 0, JobSystem::workerCount() );
+
+ for( Int round = 0; round < 3; ++round )
+ {
+ JobSystem::init( 3 );
+ CHECK_EQ( 3, JobSystem::workerCount() );
+
+ JobSystem::init( 8 ); // already running: ignored, not a second pool
+ CHECK_EQ( 3, JobSystem::workerCount() );
+
+ resetJobVisits();
+ JobSystem::parallel_for( 200, 1, jobTestCount, NULL );
+ for( Int i = 0; i < 200; ++i )
+ CHECK_EQ( 1, s_jobVisits[ i ] );
+
+ JobSystem::shutdown();
+ CHECK_EQ( 0, JobSystem::workerCount() );
+
+ // and with the pool down, the same call still covers the range
+ resetJobVisits();
+ JobSystem::parallel_for( 200, 1, jobTestCount, NULL );
+ for( Int i = 0; i < 200; ++i )
+ CHECK_EQ( 1, s_jobVisits[ i ] );
+ }
+}