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

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

@@ -44,5 +44,5 @@ int main() {
}); });
spdlog::info("Waiting for connection..."); spdlog::info("Waiting for connection...");
sock.accept(clientSock, clientAddr); // sock.accept(clientSock, clientAddr);
} }

View File

@@ -1,2 +1,15 @@
#include "Utils/Thread.hpp" #include "Utils/Thread.hpp"
namespace Chattr {
Thread::~Thread() {
join();
}
void Thread::join() {
#ifdef _WIN32
WaitForSingleObject(handle_, INFINITE);
#elif __linux__
pthread_join(handle_, NULL);
#endif
}
}

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#ifdef _WIN32 #ifdef _WIN32
#include <windows.h> #include <windows.h>
#include <process.h>
#elif __linux__ #elif __linux__
#include <pthread.h> #include <pthread.h>
#else #else
@@ -13,7 +14,7 @@ namespace Chattr {
class Thread { class Thread {
public: public:
#ifdef _WIN32 #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)); std::unique_ptr<std::function<void()>> func(static_cast<std::function<void()>*>(param));
(*func)(); (*func)();
return 0; return 0;
@@ -26,7 +27,20 @@ public:
} }
#endif #endif
template<typename Callable, typename... Args> 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: private:
#ifdef _WIN32 #ifdef _WIN32
@@ -36,17 +50,4 @@ private:
#endif #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 } // namespace Chattr