platform_thread_win.cc (2514B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style license that can be 5 // found in the LICENSE file. 6 7 #include "base/platform_thread.h" 8 9 #include "base/logging.h" 10 #include "base/win_util.h" 11 12 #include "nsThreadUtils.h" 13 14 namespace { 15 16 DWORD __stdcall ThreadFunc(void* closure) { 17 PlatformThread::Delegate* delegate = 18 static_cast<PlatformThread::Delegate*>(closure); 19 delegate->ThreadMain(); 20 return 0; 21 } 22 23 } // namespace 24 25 // static 26 PlatformThreadId PlatformThread::CurrentId() { return GetCurrentThreadId(); } 27 28 // static 29 void PlatformThread::YieldCurrentThread() { ::Sleep(0); } 30 31 // static 32 void PlatformThread::Sleep(int duration_ms) { ::Sleep(duration_ms); } 33 34 // static 35 void PlatformThread::SetName(const char* name) { 36 // Using NS_SetCurrentThreadName, as opposed to using platform APIs directly, 37 // also sets the thread name on the PRThread wrapper, and allows us to 38 // retrieve it using PR_GetThreadName. 39 NS_SetCurrentThreadName(name); 40 } 41 42 // static 43 bool PlatformThread::Create(size_t stack_size, Delegate* delegate, 44 PlatformThreadHandle* thread_handle) { 45 unsigned int flags = 0; 46 if (stack_size > 0) { 47 flags = STACK_SIZE_PARAM_IS_A_RESERVATION; 48 } else { 49 stack_size = 0; 50 } 51 52 // Using CreateThread here vs _beginthreadex makes thread creation a bit 53 // faster and doesn't require the loader lock to be available. Our code will 54 // have to work running on CreateThread() threads anyway, since we run code 55 // on the Windows thread pool, etc. For some background on the difference: 56 // http://www.microsoft.com/msj/1099/win32/win321099.aspx 57 *thread_handle = 58 CreateThread(NULL, stack_size, ThreadFunc, delegate, flags, NULL); 59 return *thread_handle != NULL; 60 } 61 62 // static 63 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) { 64 PlatformThreadHandle thread_handle; 65 bool result = Create(stack_size, delegate, &thread_handle); 66 CloseHandle(thread_handle); 67 return result; 68 } 69 70 // static 71 void PlatformThread::Join(PlatformThreadHandle thread_handle) { 72 DCHECK(thread_handle); 73 74 // Wait for the thread to exit. It should already have terminated but make 75 // sure this assumption is valid. 76 DWORD result = WaitForSingleObject(thread_handle, INFINITE); 77 DCHECK_EQ(WAIT_OBJECT_0, result); 78 79 CloseHandle(thread_handle); 80 }