| 54 | } |
| 55 | |
| 56 | void *thread_init(void (*threadfunc)(void *), void *u, const char *name) |
| 57 | { |
| 58 | struct THREAD_RUN *data = (THREAD_RUN *)malloc(sizeof(*data)); |
| 59 | data->threadfunc = threadfunc; |
| 60 | data->u = u; |
| 61 | #if defined(CONF_FAMILY_UNIX) |
| 62 | { |
| 63 | pthread_attr_t attr; |
| 64 | dbg_assert(pthread_attr_init(&attr) == 0, "pthread_attr_init failure"); |
| 65 | #if defined(CONF_PLATFORM_MACOS) && defined(__MAC_10_10) && __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_10 |
| 66 | dbg_assert(pthread_attr_set_qos_class_np(&attr, QOS_CLASS_USER_INTERACTIVE, 0) == 0, "pthread_attr_set_qos_class_np failure"); |
| 67 | #endif |
| 68 | pthread_t id; |
| 69 | dbg_assert(pthread_create(&id, &attr, thread_run, data) == 0, "pthread_create failure"); |
| 70 | #if defined(CONF_PLATFORM_EMSCRIPTEN) |
| 71 | // Return control to the browser's main thread to allow the pthread to be started, |
| 72 | // otherwise we deadlock when waiting for a thread immediately after starting it. |
| 73 | emscripten_sleep(0); |
| 74 | #endif |
| 75 | return (void *)id; |
| 76 | } |
| 77 | #elif defined(CONF_FAMILY_WINDOWS) |
| 78 | HANDLE thread = CreateThread(nullptr, 0, thread_run, data, 0, nullptr); |
| 79 | dbg_assert(thread != nullptr, "CreateThread failure"); |
| 80 | HMODULE kernel_base_handle; |
| 81 | if(GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, L"KernelBase.dll", &kernel_base_handle)) |
| 82 | { |
| 83 | // Intentional |
| 84 | #ifdef __MINGW32__ |
| 85 | #pragma GCC diagnostic push |
| 86 | #pragma GCC diagnostic ignored "-Wcast-function-type" |
| 87 | #endif |
| 88 | auto set_thread_description_function = reinterpret_cast<HRESULT(WINAPI *)(HANDLE, PCWSTR)>(GetProcAddress(kernel_base_handle, "SetThreadDescription")); |
| 89 | #ifdef __MINGW32__ |
| 90 | #pragma GCC diagnostic pop |
| 91 | #endif |
| 92 | if(set_thread_description_function) |
| 93 | set_thread_description_function(thread, windows_utf8_to_wide(name).c_str()); |
| 94 | } |
| 95 | return thread; |
| 96 | #else |
| 97 | #error not implemented |
| 98 | #endif |
| 99 | } |
| 100 | |
| 101 | void thread_wait(void *thread) |
| 102 | { |