jak-project/game/system/SystemThread.h

88 lines
1.9 KiB
C
Raw Normal View History

#pragma once
2020-08-22 22:30:12 -04:00
/*!
* @file SystemThread.h
* Threads for the runtime.
*/
#ifndef RUNTIME_SYSTEMTHREAD_H
#define RUNTIME_SYSTEMTHREAD_H
#include <array>
#include <condition_variable>
#include <functional>
2020-08-22 22:30:12 -04:00
#include <mutex>
#include <string>
2020-09-03 23:56:35 -04:00
#include <thread>
#include "common/util/Timer.h"
2020-08-22 22:30:12 -04:00
constexpr int MAX_SYSTEM_THREADS = 16;
class SystemThreadInterface;
class SystemThreadManager;
/*!
* Runs a function in a thread and provides a SystemThreadInterface to that function.
* Once the thread is ready, it should tell the interface with intitialization_complete().
2020-08-22 22:30:12 -04:00
* Thread functions should try to return when get_want_exit() returns true.
*/
class SystemThread {
2020-08-26 01:21:33 -04:00
public:
2020-08-22 22:30:12 -04:00
void start(std::function<void(SystemThreadInterface&)> f);
void join();
void stop();
SystemThread() = default;
2020-08-26 01:21:33 -04:00
private:
2020-08-22 22:30:12 -04:00
friend class SystemThreadInterface;
friend class SystemThreadManager;
friend void* bootstrap_thread_func(void* thd);
std::string name = "invalid";
std::thread thread;
2020-08-22 22:30:12 -04:00
SystemThreadManager* manager;
2020-08-26 01:21:33 -04:00
std::function<void(SystemThreadInterface&)> function;
2020-08-22 22:30:12 -04:00
bool initialization_complete = false;
std::mutex initialization_mutex;
std::condition_variable initialization_cv;
Timer stats_timer;
Timer stat_diff_timer;
double cpu_user = 0, cpu_kernel = 0;
int id = -1;
bool want_exit = false;
bool running = false;
};
/*!
* The interface used by a thread in the runtime.
2020-08-22 22:30:12 -04:00
*/
class SystemThreadInterface {
2020-08-26 01:21:33 -04:00
public:
SystemThreadInterface(SystemThread* p) : thread(*p) {}
2020-08-22 22:30:12 -04:00
void initialization_complete();
bool get_want_exit() const;
void trigger_shutdown();
2020-08-26 01:21:33 -04:00
private:
2020-08-22 22:30:12 -04:00
SystemThread& thread;
};
/*!
* A manager of all threads in the runtime.
*/
class SystemThreadManager {
2020-08-26 01:21:33 -04:00
public:
2020-08-22 22:30:12 -04:00
SystemThread& create_thread(const std::string& name);
void print_stats();
void shutdown();
void join();
bool all_threads_exiting();
2020-08-26 01:21:33 -04:00
private:
2020-08-22 22:30:12 -04:00
std::array<SystemThread, MAX_SYSTEM_THREADS> threads;
int thread_count = 0;
};
2020-08-26 01:21:33 -04:00
#endif // RUNTIME_SYSTEMTHREAD_H