1 //===-- llvm/Support/Threading.cpp- Control multithreading mode --*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines helper functions for running LLVM in a multi-threaded
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/Threading.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/Support/Atomic.h"
18 #include "llvm/Support/Mutex.h"
23 bool llvm::llvm_is_multithreaded() {
24 #if LLVM_ENABLE_THREADS != 0
31 #if LLVM_ENABLE_THREADS != 0 && defined(HAVE_PTHREAD_H)
35 void (*UserFn)(void *);
38 static void *ExecuteOnThread_Dispatch(void *Arg) {
39 ThreadInfo *TI = reinterpret_cast<ThreadInfo*>(Arg);
40 TI->UserFn(TI->UserData);
44 void llvm::llvm_execute_on_thread(void (*Fn)(void*), void *UserData,
45 unsigned RequestedStackSize) {
46 ThreadInfo Info = { Fn, UserData };
50 // Construct the attributes object.
51 if (::pthread_attr_init(&Attr) != 0)
54 // Set the requested stack size, if given.
55 if (RequestedStackSize != 0) {
56 if (::pthread_attr_setstacksize(&Attr, RequestedStackSize) != 0)
60 // Construct and execute the thread.
61 if (::pthread_create(&Thread, &Attr, ExecuteOnThread_Dispatch, &Info) != 0)
64 // Wait for the thread and clean up.
65 ::pthread_join(Thread, nullptr);
68 ::pthread_attr_destroy(&Attr);
70 #elif LLVM_ENABLE_THREADS!=0 && defined(LLVM_ON_WIN32)
71 #include "Windows/WindowsSupport.h"
79 static unsigned __stdcall ThreadCallback(void *param) {
80 struct ThreadInfo *info = reinterpret_cast<struct ThreadInfo *>(param);
81 info->func(info->param);
86 void llvm::llvm_execute_on_thread(void (*Fn)(void*), void *UserData,
87 unsigned RequestedStackSize) {
88 struct ThreadInfo param = { Fn, UserData };
90 HANDLE hThread = (HANDLE)::_beginthreadex(NULL,
91 RequestedStackSize, ThreadCallback,
95 // We actually don't care whether the wait succeeds or fails, in
96 // the same way we don't care whether the pthread_join call succeeds
97 // or fails. There's not much we could do if this were to fail. But
98 // on success, this call will wait until the thread finishes executing
100 (void)::WaitForSingleObject(hThread, INFINITE);
101 ::CloseHandle(hThread);
105 // Support for non-Win32, non-pthread implementation.
106 void llvm::llvm_execute_on_thread(void (*Fn)(void*), void *UserData,
107 unsigned RequestedStackSize) {
108 (void) RequestedStackSize;