← C++

C++ · 09 / 24

Background work, performance and desktop packages

Observe a stoppable simulation service and verify measurable, distributable software.

  • Large
  • Advanced
  • 120 min

Prerequisites: Classes, references, const and RAII, Headers, CMake and first unit tests, A* routing and deterministic transport simulation

In this tutorial
  1. Build the example and dependencies
  2. Verify pause and manual steps
  3. Read background progress and snapshots
  4. Stop in a controlled order
  5. Measure a defined performance workload
  6. Inspect the verification
  7. Check the package on its target platform
  8. Exercise and solution
  9. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-21 on Linux x86_64. The real simulation service is started and stopped. The solution repeats pause, single-step and stop twenty times. Windows delivery remains unverified.

The window must continue processing input during computation, so the app uses a background service. Threads share memory within one process. That enables state exchange but requires an explicit synchronization policy. A mutex protects simulation access and snapshot copies here.

std::jthread supports an orderly stop through stop_token. Requesting a stop does not magically terminate work. The worker must observe the token and its waiting point must be able to wake up. This lesson uses the real SimulationService. It first verifies manual steps and then completes the remaining deliveries in the background.

Package contents and individual files

01Build the example and dependencies

Extract the learning package. The required FactoryForge sources are included under vendor from the linked pinned revision. Run cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug and cmake --build build. This standalone check does not require an additional full project download.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(ThreadLesson LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
get_filename_component(FACTORYFORGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/vendor/factory-forge" ABSOLUTE CACHE)
find_package(Threads REQUIRED)
add_executable(lesson main.cpp
  "${FACTORYFORGE_SOURCE_DIR}/src/core/project.cpp"
  "${FACTORYFORGE_SOURCE_DIR}/src/core/pathfinder.cpp"
  "${FACTORYFORGE_SOURCE_DIR}/src/core/puzzles.cpp"
  "${FACTORYFORGE_SOURCE_DIR}/src/core/simulation.cpp"
  "${FACTORYFORGE_SOURCE_DIR}/src/application/simulation_service.cpp")
target_include_directories(lesson PRIVATE "${FACTORYFORGE_SOURCE_DIR}/include")
target_link_libraries(lesson PRIVATE Threads::Threads)

02Verify pause and manual steps

start receives a reference solution and false for initial playback. The service owns a simulation but does not yet advance automatically. Twenty calls to stepOnce produce exactly twenty logical ticks. This is a verifiable business result, independent of how quickly the host runs the loop.

main.cpp · cppOpen file
#include "factory/application/simulation_service.h"
#include "factory/core/puzzles.h"
#include <chrono>
#include <iostream>
#include <thread>
int main() {
  factory::SimulationService service;
  service.start(factory::makePuzzle(0, true), false);
  for (int i = 0; i < 20; ++i)
    service.stepOnce();
  std::cout << "manual_ticks=" << service.snapshot().tick << '\n';
  service.setSpeed(4);
  service.setPlaying(true);
  const auto deadline =
      std::chrono::steady_clock::now() + std::chrono::seconds(10);
  while (service.snapshot().outcome == factory::Outcome::Running &&
         std::chrono::steady_clock::now() < deadline)
    std::this_thread::sleep_for(std::chrono::milliseconds(5));
  const auto snapshot = service.snapshot();
  service.stop();
  std::cout << "delivered=" << snapshot.delivered << '\n';
  std::cout << std::boolalpha << "stopped=" << !service.active() << '\n';
  return snapshot.outcome == factory::Outcome::Won ? 0 : 1;
}

Run / check

cmake -S . -B build -G Ninja -DFACTORYFORGE_SOURCE_DIR=/path/to/factory-forge
cmake --build build
./build/lesson
Expected result

manual_ticks=20

03Read background progress and snapshots

setSpeed(4) and setPlaying(true) resume automatic work. snapshot returns a protected value. The caller can read that copy without writing into live vehicle data. A small sleep avoids a busy polling loop in this teaching program. Its extra deadline prevents a broken demonstration from waiting forever.

04Stop in a controlled order

stop requests cancellation, wakes the condition variable and waits for thread completion. The simulation is released afterwards. Do not call join while holding a mutex the worker still needs to finish. Execute the example and check deliveries as well as tick count and lifecycle.

Expected result

manual_ticks=20 delivered=3 stopped=true

05Measure a defined performance workload

Build in Release mode and run factoryforge-cli --benchmark 50. Its report names the scenario, vehicle count, deliveries and mean/peak step time. The included measurements exclude rendering and real-time waiting. Compare the same build and machine. One fast demonstration cannot guarantee performance for arbitrary maps.

06Inspect the verification

The real simulation service is started and stopped. The solution repeats pause, single-step and stop twenty times. Windows delivery remains unverified.Run python3 run_checks.py from the extracted package. Compare the test expectations with the exercise before opening the solution.

Expected result

The example and automated solution pass. The stated manual checks remain separate.

07Check the package on its target platform

The Linux package contains the app, CLI, Qt runtime, puzzles and licence texts. Its launcher uses relative library paths. The Windows helper uses windeployqt and the prepared native build matrix. Compilation alone is not package verification. Run the bundled GUI and CLI. Windows evidence remains pending until genuine native verification.

Your exercise

Repeatedly start, pause, single-step and stop the service. Also compare Debug and Release benchmarks without presenting one result as a universal speed multiplier.

Show the solution and explanation

Every new run starts from the original layout. Paused ticks do not change unless explicitly stepped. stop completes the worker and active becomes false. The application test repeats the lifecycle twenty times. Record build type, hardware and workload for performance comparisons. These observations do not replace target-platform verification.

solution/main.cpp · cppOpen file
#include "factory/application/simulation_service.h"
#include "factory/core/puzzles.h"
#include <cassert>
#include <chrono>
#include <iostream>
#include <thread>
int main() {
  factory::SimulationService service;
  for (int run = 0; run < 20; ++run) {
    service.start(factory::makePuzzle(0, true), false);
    assert(service.snapshot().tick == 0);
    service.stepOnce();
    const auto paused = service.snapshot().tick;
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    assert(service.snapshot().tick == paused);
    service.stop();
    assert(!service.active());
  }
  service.start(factory::makePuzzle(0, true), false);
  for (int i = 0; i < 20; ++i)
    service.stepOnce();
  std::cout << "manual_ticks=" << service.snapshot().tick << '\n';
  service.setSpeed(4);
  service.setPlaying(true);
  const auto deadline =
      std::chrono::steady_clock::now() + std::chrono::seconds(10);
  while (service.snapshot().outcome == factory::Outcome::Running &&
         std::chrono::steady_clock::now() < deadline)
    std::this_thread::sleep_for(std::chrono::milliseconds(5));
  const auto snapshot = service.snapshot();
  service.stop();
  std::cout << "delivered=" << snapshot.delivered << '\n';
  std::cout << std::boolalpha << "stopped=" << !service.active() << '\n';
  return snapshot.outcome == factory::Outcome::Won ? 0 : 1;
}

Project context and sources

The first six examples are standalone teaching programs. Lessons 7 through 9 use the complete FactoryForge source snapshot. Code, exercises and verified simplifications are explained separately. The project page provides a source ZIP while the GitHub repository is not yet published.