Crafter.Thread/interfaces/Crafter.Thread-ThreadPool.cppm

37 lines
1.3 KiB
Text
Raw Normal View History

//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Crafter.Thread:ThreadPool;
import std;
namespace Crafter {
struct ThreadStorage {
std::vector<std::function<void(void)>> tasks;
std::vector<std::function<void(void)>> buffer;
std::condition_variable cv;
std::mutex mutex;
std::atomic<unsigned int> taskCount;
std::thread thread;
};
export class ThreadPool {
public:
static inline std::atomic<bool> stopped;
static void Start(int maxThreads = -1);
// Stops the workers, each once it has run what it was given, and ends
// a JoinPool; a task enqueued once Stop has begun may not run. From
// one thread at a time, not the pool's own: a task can't stop the
// pool it runs in. Again, or before Start, it does nothing. JoinPool
// can return before Stop has: Start a new pool once Stop returned.
static void Stop();
static void Enqueue(std::function<void(void)> task);
static void Enqueue(std::vector<std::function<void(void)>> tasks);
static void JoinPool();
static inline unsigned int threadCount;
static inline std::atomic<unsigned int> activeThreads;
private:
static inline std::unordered_map<std::thread::id, ThreadStorage*> threadIdMap;
static inline ThreadStorage* threadStorage;
static void WaitAndExecuteTask(ThreadStorage* threadStorage);
};
2025-02-17 22:31:53 +01:00
}