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