Index: src/untrusted/init/thread.cc |
diff --git a/src/untrusted/init/thread.cc b/src/untrusted/init/thread.cc |
new file mode 100644 |
index 0000000000000000000000000000000000000000..706fb2ca710c0e0dc097e98e29319ed991501c97 |
--- /dev/null |
+++ b/src/untrusted/init/thread.cc |
@@ -0,0 +1,106 @@ |
+// Copyright (c) 2013 The Native Client Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#include "native_client/src/untrusted/init/thread_interface.h" |
+ |
+#include <pthread.c> |
+ |
+namespace nacl { |
+ |
+Thread::Thread(ThreadFactoryFunction factory, |
+ void *factory_data, |
+ ThreadStartFunction start_routine, |
+ void *startup_data) |
+ : started_(false), |
+ stopping_(false), |
+ running_(false), |
+ startup_data_(NULL), |
+ factory_(factory), |
+ factory_data_(factory_data), |
+ start_routine_(start_routine), |
+ startup_data_(startup_data) { |
+} |
+ |
+Thread::~Thread() { |
+ //CHECK(!thread_started_); |
+ //start_routine_ = NULL; |
+ //thread_data_ = NULL; |
+ Stop(); |
+} |
+ |
+static void *ThreadStart(void *data) { |
+ Thread *interface = |
+ reinterpret_cast<Thread *>(data); |
+ interface->LaunchCallback(); |
+ void *thread_return = interface->start_routine_(); |
+ interface->Exit(thread_return); |
+} |
+ |
+int Thread::Start() { |
+ CHECK(!thread_started_); |
+ int retval = pthread_create(&thread_, NULL, ThreadStart, this); |
+ if (retval == 0) { |
+ thread_started_ = true; |
+ } |
+ return retval; |
+} |
+ |
+void Thread::Stop() { |
+ if (!started_) { |
+ return; |
+ } |
+ |
+ // Wait for the thread to exit. |
+ pthread_join(thread_); |
+ |
+ started_ = false; |
+ stopping_ = false; |
+} |
+ |
+void Thread::StopSoon() { |
+ if (stopping_) { |
+ return; |
+ } |
+ |
+ stopping_ = true; |
+} |
+ |
+void Thread::Exit(void *thread_return) { |
+ thread_started_ = 0; |
+ Unref(); |
+ pthread_exit(thread_return); |
+} |
+ |
+Thread *ThreadConstructAndStartThread( |
+ ThreadFactoryFunction factory, |
+ void *factory_data, |
+ ThreadStartFunction start_routine, |
+ void *thread_data) { |
+ Thread *thread; |
+ if ((thread = (*factory)(factory_data, |
+ start_routine, |
+ thread_data)) == NULL) { |
+ goto out; |
+ } |
+ if (!thread->Start()) { |
+ thread->Unref(); |
+ goto out; |
+ } |
+ out: |
+ return thread; |
+} |
+ |
+Thread *ThreadThreadFactory( |
+ void *factory_data, |
+ ThreadStartFunction start_routine, |
+ void *thread_data) { |
+ Thread *thread = new Thread( |
+ ThreadThreadFactory, |
+ factory_data, |
+ start_routine, |
+ thread_data); |
+ return thread; |
+} |
+ |
+} // namespace nacl |