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/Host.h"
19 #include "llvm/Support/Mutex.h"
20 #include "llvm/Support/thread.h"
25 bool llvm::llvm_is_multithreaded() {
26 #if LLVM_ENABLE_THREADS != 0
33 #if LLVM_ENABLE_THREADS != 0 && defined(HAVE_PTHREAD_H)
37 void (*UserFn)(void *);
40 static void *ExecuteOnThread_Dispatch(void *Arg) {
41 ThreadInfo *TI = reinterpret_cast<ThreadInfo*>(Arg);
42 TI->UserFn(TI->UserData);
46 void llvm::llvm_execute_on_thread(void (*Fn)(void*), void *UserData,
47 unsigned RequestedStackSize) {
48 ThreadInfo Info = { Fn, UserData };
52 // Construct the attributes object.
53 if (::pthread_attr_init(&Attr) != 0)
56 // Set the requested stack size, if given.
57 if (RequestedStackSize != 0) {
58 if (::pthread_attr_setstacksize(&Attr, RequestedStackSize) != 0)
62 // Construct and execute the thread.
63 if (::pthread_create(&Thread, &Attr, ExecuteOnThread_Dispatch, &Info) != 0)
66 // Wait for the thread and clean up.
67 ::pthread_join(Thread, nullptr);
70 ::pthread_attr_destroy(&Attr);
72 #elif LLVM_ENABLE_THREADS!=0 && defined(LLVM_ON_WIN32)
73 #include "Windows/WindowsSupport.h"
76 // Windows will at times define MemoryFence.
86 static unsigned __stdcall ThreadCallback(void *param) {
87 struct ThreadInfo *info = reinterpret_cast<struct ThreadInfo *>(param);
88 info->func(info->param);
93 void llvm::llvm_execute_on_thread(void (*Fn)(void*), void *UserData,
94 unsigned RequestedStackSize) {
95 struct ThreadInfo param = { Fn, UserData };
97 HANDLE hThread = (HANDLE)::_beginthreadex(NULL,
98 RequestedStackSize, ThreadCallback,
102 // We actually don't care whether the wait succeeds or fails, in
103 // the same way we don't care whether the pthread_join call succeeds
104 // or fails. There's not much we could do if this were to fail. But
105 // on success, this call will wait until the thread finishes executing
107 (void)::WaitForSingleObject(hThread, INFINITE);
108 ::CloseHandle(hThread);
112 // Support for non-Win32, non-pthread implementation.
113 void llvm::llvm_execute_on_thread(void (*Fn)(void*), void *UserData,
114 unsigned RequestedStackSize) {
115 (void) RequestedStackSize;
121 unsigned llvm::heavyweight_hardware_concurrency() {
122 #if !LLVM_ENABLE_THREADS
125 int NumPhysical = sys::getHostNumPhysicalCores();
126 if (NumPhysical == -1)
127 return thread::hardware_concurrency();