Apply the initial thread priority on the starting thread on Windows
[chromium-blink-merge.git] / base / threading / platform_thread_win.cc
blobc2eab6ccfd3e7462ec9816dee32ef54204c0f3f7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/threading/platform_thread.h"
7 #include "base/debug/alias.h"
8 #include "base/debug/profiler.h"
9 #include "base/logging.h"
10 #include "base/threading/thread_id_name_manager.h"
11 #include "base/threading/thread_restrictions.h"
12 #include "base/tracked_objects.h"
13 #include "base/win/scoped_handle.h"
14 #include "base/win/windows_version.h"
16 namespace base {
18 namespace {
20 // The information on how to set the thread name comes from
21 // a MSDN article: http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx
22 const DWORD kVCThreadNameException = 0x406D1388;
24 typedef struct tagTHREADNAME_INFO {
25 DWORD dwType; // Must be 0x1000.
26 LPCSTR szName; // Pointer to name (in user addr space).
27 DWORD dwThreadID; // Thread ID (-1=caller thread).
28 DWORD dwFlags; // Reserved for future use, must be zero.
29 } THREADNAME_INFO;
31 // This function has try handling, so it is separated out of its caller.
32 void SetNameInternal(PlatformThreadId thread_id, const char* name) {
33 THREADNAME_INFO info;
34 info.dwType = 0x1000;
35 info.szName = name;
36 info.dwThreadID = thread_id;
37 info.dwFlags = 0;
39 __try {
40 RaiseException(kVCThreadNameException, 0, sizeof(info)/sizeof(DWORD),
41 reinterpret_cast<DWORD_PTR*>(&info));
42 } __except(EXCEPTION_CONTINUE_EXECUTION) {
46 struct ThreadParams {
47 PlatformThread::Delegate* delegate;
48 bool joinable;
49 ThreadPriority priority;
52 DWORD __stdcall ThreadFunc(void* params) {
53 ThreadParams* thread_params = static_cast<ThreadParams*>(params);
54 PlatformThread::Delegate* delegate = thread_params->delegate;
55 if (!thread_params->joinable)
56 base::ThreadRestrictions::SetSingletonAllowed(false);
58 if (thread_params->priority != ThreadPriority::NORMAL) {
59 PlatformThread::SetThreadPriority(
60 PlatformThread::CurrentHandle(), thread_params->priority);
63 // Retrieve a copy of the thread handle to use as the key in the
64 // thread name mapping.
65 PlatformThreadHandle::Handle platform_handle;
66 BOOL did_dup = DuplicateHandle(GetCurrentProcess(),
67 GetCurrentThread(),
68 GetCurrentProcess(),
69 &platform_handle,
71 FALSE,
72 DUPLICATE_SAME_ACCESS);
74 win::ScopedHandle scoped_platform_handle;
76 if (did_dup) {
77 scoped_platform_handle.Set(platform_handle);
78 ThreadIdNameManager::GetInstance()->RegisterThread(
79 scoped_platform_handle.Get(),
80 PlatformThread::CurrentId());
83 delete thread_params;
84 delegate->ThreadMain();
86 if (did_dup) {
87 ThreadIdNameManager::GetInstance()->RemoveName(
88 scoped_platform_handle.Get(),
89 PlatformThread::CurrentId());
92 return NULL;
95 // CreateThreadInternal() matches PlatformThread::CreateWithPriority(), except
96 // that |out_thread_handle| may be NULL, in which case a non-joinable thread is
97 // created.
98 bool CreateThreadInternal(size_t stack_size,
99 PlatformThread::Delegate* delegate,
100 PlatformThreadHandle* out_thread_handle,
101 ThreadPriority priority) {
102 unsigned int flags = 0;
103 if (stack_size > 0 && base::win::GetVersion() >= base::win::VERSION_XP) {
104 flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
105 } else {
106 stack_size = 0;
109 ThreadParams* params = new ThreadParams;
110 params->delegate = delegate;
111 params->joinable = out_thread_handle != NULL;
112 params->priority = priority;
114 // Using CreateThread here vs _beginthreadex makes thread creation a bit
115 // faster and doesn't require the loader lock to be available. Our code will
116 // have to work running on CreateThread() threads anyway, since we run code
117 // on the Windows thread pool, etc. For some background on the difference:
118 // http://www.microsoft.com/msj/1099/win32/win321099.aspx
119 PlatformThreadId thread_id;
120 void* thread_handle = CreateThread(
121 NULL, stack_size, ThreadFunc, params, flags, &thread_id);
122 if (!thread_handle) {
123 delete params;
124 return false;
127 if (out_thread_handle)
128 *out_thread_handle = PlatformThreadHandle(thread_handle, thread_id);
129 else
130 CloseHandle(thread_handle);
131 return true;
134 } // namespace
136 // static
137 PlatformThreadId PlatformThread::CurrentId() {
138 return ::GetCurrentThreadId();
141 // static
142 PlatformThreadRef PlatformThread::CurrentRef() {
143 return PlatformThreadRef(::GetCurrentThreadId());
146 // static
147 PlatformThreadHandle PlatformThread::CurrentHandle() {
148 return PlatformThreadHandle(::GetCurrentThread());
151 // static
152 void PlatformThread::YieldCurrentThread() {
153 ::Sleep(0);
156 // static
157 void PlatformThread::Sleep(TimeDelta duration) {
158 // When measured with a high resolution clock, Sleep() sometimes returns much
159 // too early. We may need to call it repeatedly to get the desired duration.
160 TimeTicks end = TimeTicks::Now() + duration;
161 for (TimeTicks now = TimeTicks::Now(); now < end; now = TimeTicks::Now())
162 ::Sleep(static_cast<DWORD>((end - now).InMillisecondsRoundedUp()));
165 // static
166 void PlatformThread::SetName(const std::string& name) {
167 ThreadIdNameManager::GetInstance()->SetName(CurrentId(), name);
169 // On Windows only, we don't need to tell the profiler about the "BrokerEvent"
170 // thread, as it exists only in the chrome.exe image, and never spawns or runs
171 // tasks (items which could be profiled). This test avoids the notification,
172 // which would also (as a side effect) initialize the profiler in this unused
173 // context, including setting up thread local storage, etc. The performance
174 // impact is not terrible, but there is no reason to do initialize it.
175 if (name != "BrokerEvent")
176 tracked_objects::ThreadData::InitializeThreadContext(name);
178 // The debugger needs to be around to catch the name in the exception. If
179 // there isn't a debugger, we are just needlessly throwing an exception.
180 // If this image file is instrumented, we raise the exception anyway
181 // to provide the profiler with human-readable thread names.
182 if (!::IsDebuggerPresent() && !base::debug::IsBinaryInstrumented())
183 return;
185 SetNameInternal(CurrentId(), name.c_str());
188 // static
189 const char* PlatformThread::GetName() {
190 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
193 // static
194 bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
195 PlatformThreadHandle* thread_handle) {
196 return CreateWithPriority(
197 stack_size, delegate, thread_handle, ThreadPriority::NORMAL);
200 // static
201 bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
202 PlatformThreadHandle* thread_handle,
203 ThreadPriority priority) {
204 DCHECK(thread_handle);
205 return CreateThreadInternal(stack_size, delegate, thread_handle, priority);
208 // static
209 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
210 return CreateThreadInternal(
211 stack_size, delegate, NULL, ThreadPriority::NORMAL);
214 // static
215 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
216 DCHECK(thread_handle.platform_handle());
217 // TODO(willchan): Enable this check once I can get it to work for Windows
218 // shutdown.
219 // Joining another thread may block the current thread for a long time, since
220 // the thread referred to by |thread_handle| may still be running long-lived /
221 // blocking tasks.
222 #if 0
223 base::ThreadRestrictions::AssertIOAllowed();
224 #endif
226 // Wait for the thread to exit. It should already have terminated but make
227 // sure this assumption is valid.
228 DWORD result = WaitForSingleObject(thread_handle.platform_handle(), INFINITE);
229 if (result != WAIT_OBJECT_0) {
230 // Debug info for bug 127931.
231 DWORD error = GetLastError();
232 debug::Alias(&error);
233 debug::Alias(&result);
234 CHECK(false);
237 CloseHandle(thread_handle.platform_handle());
240 // static
241 void PlatformThread::SetThreadPriority(PlatformThreadHandle handle,
242 ThreadPriority priority) {
243 DCHECK(!handle.is_null());
245 int desired_priority = THREAD_PRIORITY_ERROR_RETURN;
246 switch (priority) {
247 case ThreadPriority::BACKGROUND:
248 desired_priority = THREAD_PRIORITY_LOWEST;
249 break;
250 case ThreadPriority::NORMAL:
251 desired_priority = THREAD_PRIORITY_NORMAL;
252 break;
253 case ThreadPriority::DISPLAY:
254 desired_priority = THREAD_PRIORITY_ABOVE_NORMAL;
255 break;
256 case ThreadPriority::REALTIME_AUDIO:
257 desired_priority = THREAD_PRIORITY_TIME_CRITICAL;
258 break;
259 default:
260 NOTREACHED() << "Unknown priority.";
261 break;
263 DCHECK_NE(desired_priority, THREAD_PRIORITY_ERROR_RETURN);
265 #ifndef NDEBUG
266 const BOOL success =
267 #endif
268 ::SetThreadPriority(handle.platform_handle(), desired_priority);
269 DPLOG_IF(ERROR, !success) << "Failed to set thread priority to "
270 << desired_priority;
273 // static
274 ThreadPriority PlatformThread::GetThreadPriority(PlatformThreadHandle handle) {
275 DCHECK(!handle.is_null());
277 int priority = ::GetThreadPriority(handle.platform_handle());
278 switch (priority) {
279 case THREAD_PRIORITY_LOWEST:
280 return ThreadPriority::BACKGROUND;
281 case THREAD_PRIORITY_NORMAL:
282 return ThreadPriority::NORMAL;
283 case THREAD_PRIORITY_ABOVE_NORMAL:
284 return ThreadPriority::DISPLAY;
285 case THREAD_PRIORITY_TIME_CRITICAL:
286 return ThreadPriority::REALTIME_AUDIO;
287 case THREAD_PRIORITY_ERROR_RETURN:
288 DPCHECK(false) << "GetThreadPriority error"; // Falls through.
289 default:
290 NOTREACHED() << "Unexpected priority: " << priority;
291 return ThreadPriority::NORMAL;
295 } // namespace base