멀티플랫폼 스레드 라이브러리 준 완성

This commit is contained in:
2025-04-24 21:15:28 +09:00
parent 85cc4ab0c5
commit 07cff49813
3 changed files with 30 additions and 16 deletions

View File

@@ -1,6 +1,7 @@
#pragma once
#ifdef _WIN32
#include <windows.h>
#include <process.h>
#elif __linux__
#include <pthread.h>
#else
@@ -13,7 +14,7 @@ namespace Chattr {
class Thread {
public:
#ifdef _WIN32
static DWORD WINAPI thread_func(LPVOID param) {
static unsigned __stdcall thread_func(LPVOID param) {
std::unique_ptr<std::function<void()>> func(static_cast<std::function<void()>*>(param));
(*func)();
return 0;
@@ -26,7 +27,20 @@ public:
}
#endif
template<typename Callable, typename... Args>
Thread(Callable&& f, Args&&... args);
Thread(Callable&& f, Args&&... args) {
auto boundFunc = std::bind(std::forward<Callable>(f), std::forward<Args>(args)...);
auto funcPtr = new std::function<void()>(boundFunc);
#ifdef _WIN32
handle_ = (HANDLE)_beginthreadex(nullptr, 0, thread_func, funcPtr, 0, nullptr);
#elif __linux__
pthread_create(&handle_, NULL, thread_func, funcPtr);
#endif
}
~Thread();
void join();
private:
#ifdef _WIN32
@@ -36,17 +50,4 @@ private:
#endif
};
template<typename Callable, typename... Args>
Thread::Thread(Callable&& f, Args&&... args) {
auto boundFunc = std::bind(std::forward<Callable>(f), std::forward<Args>(args)...);
auto funcPtr = new std::function<void()>(boundFunc);
#ifdef _WIN32
handle_ = CreateThread(nullptr, 0, thread_func, funcPtr, 0, nullptr);
#elif __linux__
pthread_create(&handle_, NULL, thread_func, funcPtr);
#endif
}
} // namespace Chattr