1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/threading/platform_thread.h"
#include <stddef.h>
#include "base/debug/activity_tracker.h"
#include "base/debug/alias.h"
#include "base/debug/profiler.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_id_name_manager.h"
#include "base/threading/thread_restrictions.h"
#include "base/tracked_objects.h"
#include "base/win/scoped_handle.h"
namespace base {
namespace {
// The information on how to set the thread name comes from
// a MSDN article: http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx
const DWORD kVCThreadNameException = 0x406D1388;
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
// The SetThreadDescription API was brought in version 1607 of Windows 10.
typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread,
PCWSTR lpThreadDescription);
// This function has try handling, so it is separated out of its caller.
void SetNameInternal(PlatformThreadId thread_id, const char* name) {
//This function is only used for debugging purposes, as you can find by its caller
#ifndef __MINGW32__
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = thread_id;
info.dwFlags = 0;
__try {
RaiseException(kVCThreadNameException, 0, sizeof(info)/sizeof(DWORD),
reinterpret_cast<DWORD_PTR*>(&info));
} __except(EXCEPTION_CONTINUE_EXECUTION) {
}
#endif
}
struct ThreadParams {
PlatformThread::Delegate* delegate;
bool joinable;
ThreadPriority priority;
};
DWORD __stdcall ThreadFunc(void* params) {
ThreadParams* thread_params = static_cast<ThreadParams*>(params);
PlatformThread::Delegate* delegate = thread_params->delegate;
if (!thread_params->joinable)
base::ThreadRestrictions::SetSingletonAllowed(false);
if (thread_params->priority != ThreadPriority::NORMAL)
PlatformThread::SetCurrentThreadPriority(thread_params->priority);
// Retrieve a copy of the thread handle to use as the key in the
// thread name mapping.
PlatformThreadHandle::Handle platform_handle;
BOOL did_dup = DuplicateHandle(GetCurrentProcess(),
GetCurrentThread(),
GetCurrentProcess(),
&platform_handle,
0,
FALSE,
DUPLICATE_SAME_ACCESS);
win::ScopedHandle scoped_platform_handle;
if (did_dup) {
scoped_platform_handle.Set(platform_handle);
ThreadIdNameManager::GetInstance()->RegisterThread(
scoped_platform_handle.Get(),
PlatformThread::CurrentId());
}
delete thread_params;
delegate->ThreadMain();
if (did_dup) {
ThreadIdNameManager::GetInstance()->RemoveName(
scoped_platform_handle.Get(),
PlatformThread::CurrentId());
}
return 0;
}
// CreateThreadInternal() matches PlatformThread::CreateWithPriority(), except
// that |out_thread_handle| may be nullptr, in which case a non-joinable thread
// is created.
bool CreateThreadInternal(size_t stack_size,
PlatformThread::Delegate* delegate,
PlatformThreadHandle* out_thread_handle,
ThreadPriority priority) {
unsigned int flags = 0;
if (stack_size > 0) {
flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
}
ThreadParams* params = new ThreadParams;
params->delegate = delegate;
params->joinable = out_thread_handle != nullptr;
params->priority = priority;
// Using CreateThread here vs _beginthreadex makes thread creation a bit
// faster and doesn't require the loader lock to be available. Our code will
// have to work running on CreateThread() threads anyway, since we run code
// on the Windows thread pool, etc. For some background on the difference:
// http://www.microsoft.com/msj/1099/win32/win321099.aspx
void* thread_handle =
::CreateThread(nullptr, stack_size, ThreadFunc, params, flags, nullptr);
if (!thread_handle) {
delete params;
return false;
}
if (out_thread_handle)
*out_thread_handle = PlatformThreadHandle(thread_handle);
else
CloseHandle(thread_handle);
return true;
}
} // namespace
// static
PlatformThreadId PlatformThread::CurrentId() {
return ::GetCurrentThreadId();
}
// static
PlatformThreadRef PlatformThread::CurrentRef() {
return PlatformThreadRef(::GetCurrentThreadId());
}
// static
PlatformThreadHandle PlatformThread::CurrentHandle() {
return PlatformThreadHandle(::GetCurrentThread());
}
// static
void PlatformThread::YieldCurrentThread() {
::Sleep(0);
}
// static
void PlatformThread::Sleep(TimeDelta duration) {
// When measured with a high resolution clock, Sleep() sometimes returns much
// too early. We may need to call it repeatedly to get the desired duration.
TimeTicks end = TimeTicks::Now() + duration;
for (TimeTicks now = TimeTicks::Now(); now < end; now = TimeTicks::Now())
::Sleep(static_cast<DWORD>((end - now).InMillisecondsRoundedUp()));
}
// static
void PlatformThread::SetName(const std::string& name) {
ThreadIdNameManager::GetInstance()->SetName(CurrentId(), name);
// On Windows only, we don't need to tell the profiler about the "BrokerEvent"
// thread, as it exists only in the chrome.exe image, and never spawns or runs
// tasks (items which could be profiled). This test avoids the notification,
// which would also (as a side effect) initialize the profiler in this unused
// context, including setting up thread local storage, etc. The performance
// impact is not terrible, but there is no reason to do initialize it.
if (name != "BrokerEvent")
tracked_objects::ThreadData::InitializeThreadContext(name);
// The SetThreadDescription API works even if no debugger is attached.
auto set_thread_description_func =
reinterpret_cast<SetThreadDescription>(::GetProcAddress(
::GetModuleHandle(L"Kernel32.dll"), "SetThreadDescription"));
if (set_thread_description_func) {
set_thread_description_func(::GetCurrentThread(),
base::UTF8ToWide(name).c_str());
}
// The debugger needs to be around to catch the name in the exception. If
// there isn't a debugger, we are just needlessly throwing an exception.
// If this image file is instrumented, we raise the exception anyway
// to provide the profiler with human-readable thread names.
if (!::IsDebuggerPresent() && !base::debug::IsBinaryInstrumented())
return;
SetNameInternal(CurrentId(), name.c_str());
}
// static
const char* PlatformThread::GetName() {
return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
}
// static
bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
PlatformThreadHandle* thread_handle,
ThreadPriority priority) {
DCHECK(thread_handle);
return CreateThreadInternal(stack_size, delegate, thread_handle, priority);
}
// static
bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
return CreateNonJoinableWithPriority(stack_size, delegate,
ThreadPriority::NORMAL);
}
// static
bool PlatformThread::CreateNonJoinableWithPriority(size_t stack_size,
Delegate* delegate,
ThreadPriority priority) {
return CreateThreadInternal(stack_size, delegate, nullptr /* non-joinable */,
priority);
}
// static
void PlatformThread::Join(PlatformThreadHandle thread_handle) {
DCHECK(thread_handle.platform_handle());
// TODO(willchan): Enable this check once I can get it to work for Windows
// shutdown.
// Joining another thread may block the current thread for a long time, since
// the thread referred to by |thread_handle| may still be running long-lived /
// blocking tasks.
#if 0
base::ThreadRestrictions::AssertIOAllowed();
#endif
DWORD thread_id = 0;
thread_id = ::GetThreadId(thread_handle.platform_handle());
DWORD last_error = 0;
if (!thread_id)
last_error = ::GetLastError();
// Record information about the exiting thread in case joining hangs.
base::debug::Alias(&thread_id);
base::debug::Alias(&last_error);
// Record the event that this thread is blocking upon (for hang diagnosis).
base::debug::ScopedThreadJoinActivity thread_activity(&thread_handle);
// Wait for the thread to exit. It should already have terminated but make
// sure this assumption is valid.
CHECK_EQ(WAIT_OBJECT_0,
WaitForSingleObject(thread_handle.platform_handle(), INFINITE));
CloseHandle(thread_handle.platform_handle());
}
// static
void PlatformThread::Detach(PlatformThreadHandle thread_handle) {
CloseHandle(thread_handle.platform_handle());
}
// static
bool PlatformThread::CanIncreaseCurrentThreadPriority() {
return true;
}
// static
void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
int desired_priority = THREAD_PRIORITY_ERROR_RETURN;
switch (priority) {
case ThreadPriority::BACKGROUND:
desired_priority = THREAD_PRIORITY_LOWEST;
break;
case ThreadPriority::NORMAL:
desired_priority = THREAD_PRIORITY_NORMAL;
break;
case ThreadPriority::DISPLAY:
desired_priority = THREAD_PRIORITY_ABOVE_NORMAL;
break;
case ThreadPriority::REALTIME_AUDIO:
desired_priority = THREAD_PRIORITY_TIME_CRITICAL;
break;
default:
NOTREACHED() << "Unknown priority.";
break;
}
DCHECK_NE(desired_priority, THREAD_PRIORITY_ERROR_RETURN);
#if DCHECK_IS_ON()
const BOOL success =
#endif
::SetThreadPriority(PlatformThread::CurrentHandle().platform_handle(),
desired_priority);
DPLOG_IF(ERROR, !success) << "Failed to set thread priority to "
<< desired_priority;
}
// static
ThreadPriority PlatformThread::GetCurrentThreadPriority() {
int priority =
::GetThreadPriority(PlatformThread::CurrentHandle().platform_handle());
switch (priority) {
case THREAD_PRIORITY_LOWEST:
return ThreadPriority::BACKGROUND;
case THREAD_PRIORITY_NORMAL:
return ThreadPriority::NORMAL;
case THREAD_PRIORITY_ABOVE_NORMAL:
return ThreadPriority::DISPLAY;
case THREAD_PRIORITY_TIME_CRITICAL:
return ThreadPriority::REALTIME_AUDIO;
case THREAD_PRIORITY_ERROR_RETURN:
DPCHECK(false) << "GetThreadPriority error"; // Falls through.
default:
NOTREACHED() << "Unexpected priority: " << priority;
return ThreadPriority::NORMAL;
}
}
} // namespace base
|