OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 #include "ppapi/utility/threading/simple_thread.h" |
| 6 |
| 7 namespace pp { |
| 8 |
| 9 namespace { |
| 10 |
| 11 struct ThreadData { |
| 12 MessageLoop_Dev message_loop; |
| 13 |
| 14 SimpleThread::ThreadFunc func; |
| 15 void* user_data; |
| 16 }; |
| 17 |
| 18 #ifdef WIN32 |
| 19 DWORD WINAPI RunThread(void* void_data) { |
| 20 #else |
| 21 void* RunThread(void* void_data) { |
| 22 #endif |
| 23 ThreadData* data = static_cast<ThreadData*>(void_data); |
| 24 data->message_loop.AttachToCurrentThread(); |
| 25 |
| 26 if (data->func) |
| 27 data->func(data->message_loop, data->user_data); |
| 28 else |
| 29 data->message_loop.Run(); |
| 30 |
| 31 delete data; |
| 32 return NULL; |
| 33 } |
| 34 |
| 35 } // namespace |
| 36 |
| 37 SimpleThread::SimpleThread(Instance* instance) |
| 38 : instance_(instance), |
| 39 message_loop_(instance), |
| 40 thread_(0) { |
| 41 } |
| 42 |
| 43 SimpleThread::~SimpleThread() { |
| 44 Join(); |
| 45 } |
| 46 |
| 47 bool SimpleThread::Start() { |
| 48 return StartWithFunction(NULL, NULL); |
| 49 } |
| 50 |
| 51 bool SimpleThread::Join() { |
| 52 if (!thread_) |
| 53 return false; |
| 54 |
| 55 message_loop_.PostQuit(true); |
| 56 |
| 57 #ifdef WIN32 |
| 58 DWORD result = WaitForSingleObject(thread_, INFINITE); |
| 59 CloseHandle(thread_); |
| 60 thread_ = 0; |
| 61 return result == WAIT_OBJECT_0; |
| 62 |
| 63 #else |
| 64 void* retval; |
| 65 int result = pthread_join(thread_, &retval); |
| 66 thread_ = 0; |
| 67 return result == 0; |
| 68 #endif |
| 69 } |
| 70 |
| 71 bool SimpleThread::StartWithFunction(ThreadFunc func, void* user_data) { |
| 72 if (thread_) |
| 73 return false; |
| 74 |
| 75 ThreadData* data = new ThreadData; |
| 76 data->message_loop = message_loop_; |
| 77 data->func = func; |
| 78 data->user_data = user_data; |
| 79 |
| 80 #ifdef WIN32 |
| 81 thread_ = CreateThread(NULL, 0, &RunThread, data, NULL); |
| 82 if (!thread_) { |
| 83 #else |
| 84 if (pthread_create(&thread_, NULL, &RunThread, data) != 0) { |
| 85 #endif |
| 86 delete data; |
| 87 return false; |
| 88 } |
| 89 return true; |
| 90 } |
| 91 |
| 92 } // namespace pp |
OLD | NEW |