Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifdef _MSC_VER
- #define NOMINMAX
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #include <tlhelp32.h>
- #else
- #include <pthread.h>
- #endif
- int is_main_thread()
- {
- #ifdef _MSC_VER
- DWORD pid = GetCurrentProcessId();
- FILETIME now;
- SYSTEMTIME st;
- GetSystemTime(&st);
- if (!SystemTimeToFileTime(&st, &now)) {
- return -1;
- }
- FILETIME oldest = now;
- DWORD oldest_tid = 0;
- std::shared_ptr<void> h(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), CloseHandle);
- if (h.get() == INVALID_HANDLE_VALUE) {
- return -1;
- }
- THREADENTRY32 te;
- te.dwSize = sizeof(te);
- if (!Thread32First(h.get(), &te)) {
- return -1;
- }
- do {
- if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) {
- if (te.th32OwnerProcessID == pid) {
- std::shared_ptr<void> th(OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, te.th32ThreadID), CloseHandle);
- if (th.get() == INVALID_HANDLE_VALUE) {
- return -1;
- }
- FILETIME creation, e, k, u;
- if (!GetThreadTimes(th.get(), &creation, &e, &k, &u)) {
- return -1;
- }
- if (oldest_tid == 0) {
- oldest = creation;
- oldest_tid = te.th32ThreadID;
- } else if (CompareFileTime(&oldest, &creation) >= 0) {
- oldest = creation;
- oldest_tid = te.th32ThreadID;
- }
- }
- }
- te.dwSize = sizeof(te);
- } while(Thread32Next(h.get(), &te));
- if (oldest_tid == 0) {
- return -1;
- }
- if (oldest_tid == GetCurrentThreadId()) {
- return 1;
- } else {
- return 0;
- }
- #else
- if (pthread_main_np() != 0) {
- return 1;
- } else {
- return 0;
- }
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement