OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2013 The Native Client 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 "native_client/src/untrusted/init/thread_interface.h" |
| 6 |
| 7 #include <pthread.c> |
| 8 |
| 9 namespace nacl { |
| 10 |
| 11 Thread::Thread(ThreadFactoryFunction factory, |
| 12 void *factory_data, |
| 13 ThreadStartFunction start_routine, |
| 14 void *startup_data) |
| 15 : started_(false), |
| 16 stopping_(false), |
| 17 running_(false), |
| 18 startup_data_(NULL), |
| 19 factory_(factory), |
| 20 factory_data_(factory_data), |
| 21 start_routine_(start_routine), |
| 22 startup_data_(startup_data) { |
| 23 } |
| 24 |
| 25 Thread::~Thread() { |
| 26 //CHECK(!thread_started_); |
| 27 //start_routine_ = NULL; |
| 28 //thread_data_ = NULL; |
| 29 Stop(); |
| 30 } |
| 31 |
| 32 static void *ThreadStart(void *data) { |
| 33 Thread *interface = |
| 34 reinterpret_cast<Thread *>(data); |
| 35 interface->LaunchCallback(); |
| 36 void *thread_return = interface->start_routine_(); |
| 37 interface->Exit(thread_return); |
| 38 } |
| 39 |
| 40 int Thread::Start() { |
| 41 CHECK(!thread_started_); |
| 42 int retval = pthread_create(&thread_, NULL, ThreadStart, this); |
| 43 if (retval == 0) { |
| 44 thread_started_ = true; |
| 45 } |
| 46 return retval; |
| 47 } |
| 48 |
| 49 void Thread::Stop() { |
| 50 if (!started_) { |
| 51 return; |
| 52 } |
| 53 |
| 54 // Wait for the thread to exit. |
| 55 pthread_join(thread_); |
| 56 |
| 57 started_ = false; |
| 58 stopping_ = false; |
| 59 } |
| 60 |
| 61 void Thread::StopSoon() { |
| 62 if (stopping_) { |
| 63 return; |
| 64 } |
| 65 |
| 66 stopping_ = true; |
| 67 } |
| 68 |
| 69 void Thread::Exit(void *thread_return) { |
| 70 thread_started_ = 0; |
| 71 Unref(); |
| 72 pthread_exit(thread_return); |
| 73 } |
| 74 |
| 75 Thread *ThreadConstructAndStartThread( |
| 76 ThreadFactoryFunction factory, |
| 77 void *factory_data, |
| 78 ThreadStartFunction start_routine, |
| 79 void *thread_data) { |
| 80 Thread *thread; |
| 81 if ((thread = (*factory)(factory_data, |
| 82 start_routine, |
| 83 thread_data)) == NULL) { |
| 84 goto out; |
| 85 } |
| 86 if (!thread->Start()) { |
| 87 thread->Unref(); |
| 88 goto out; |
| 89 } |
| 90 out: |
| 91 return thread; |
| 92 } |
| 93 |
| 94 Thread *ThreadThreadFactory( |
| 95 void *factory_data, |
| 96 ThreadStartFunction start_routine, |
| 97 void *thread_data) { |
| 98 Thread *thread = new Thread( |
| 99 ThreadThreadFactory, |
| 100 factory_data, |
| 101 start_routine, |
| 102 thread_data); |
| 103 return thread; |
| 104 } |
| 105 |
| 106 } // namespace nacl |
OLD | NEW |