Skip to content

Instantly share code, notes, and snippets.

@kbinani
Last active February 21, 2017 05:50
Show Gist options
  • Save kbinani/77975fde1a6283461232f6f08b2735b8 to your computer and use it in GitHub Desktop.
Save kbinani/77975fde1a6283461232f6f08b2735b8 to your computer and use it in GitHub Desktop.
#ifdef _MSC_VER
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tlhelp32.h>
#else
#include <pthread.h>
#endif
#include <memory>
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)) {
continue;
}
if (te.th32OwnerProcessID != pid) {
continue;
}
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;
}
} while((te.dwSize = sizeof(te)) && 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment