Home | History | Annotate | Download | only in threading
      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 #ifndef PPAPI_UTILITY_THREADING_SIMPLE_THREAD_H_
      6 #define PPAPI_UTILITY_THREADING_SIMPLE_THREAD_H_
      7 
      8 #ifdef WIN32
      9 #include <windows.h>
     10 #else
     11 #include <pthread.h>
     12 #endif
     13 
     14 #include "ppapi/cpp/instance_handle.h"
     15 #include "ppapi/cpp/message_loop.h"
     16 
     17 namespace pp {
     18 
     19 // This class is a simple wrapper around a pthread/Windows thread that creates
     20 // and runs a PPAPI message loop on that thread.
     21 class SimpleThread {
     22  public:
     23 #ifdef WIN32
     24   typedef HANDLE ThreadHandle;
     25 #else
     26   typedef pthread_t ThreadHandle;
     27 #endif
     28 
     29   typedef void (*ThreadFunc)(MessageLoop&, void* user_data);
     30 
     31   explicit SimpleThread(const InstanceHandle& instance);
     32   explicit SimpleThread(const InstanceHandle& instance, size_t stacksize);
     33   ~SimpleThread();
     34 
     35   // Starts a thread and runs a message loop in it. If you need control over
     36   // how the message loop is run, use StartWithFunction. Returns true on
     37   // success, false if the thread is already running or couldn't be started.
     38   bool Start();
     39 
     40   // Posts a quit message to the message loop and blocks until the thread
     41   // exits. Returns true on success. If the thread is not running, returns
     42   // false.
     43   bool Join();
     44 
     45   // Normally you can just use Start() to start a thread, and then post work to
     46   // it. In some cases you will want control over the message. If ThreadFunc
     47   // is NULL, this acts the same as Start().
     48   bool StartWithFunction(ThreadFunc func, void* user_data);
     49 
     50   MessageLoop& message_loop() { return message_loop_; }
     51   ThreadHandle thread() const { return thread_; }
     52 
     53  private:
     54   InstanceHandle instance_;
     55   MessageLoop message_loop_;
     56   const size_t stacksize_;
     57   ThreadHandle thread_;
     58 
     59   // Disallow (not implemented).
     60   SimpleThread(const SimpleThread&);
     61   SimpleThread(const SimpleThread&, size_t stacksize);
     62   SimpleThread& operator=(const SimpleThread&);
     63 };
     64 
     65 }  // namespace pp
     66 
     67 #endif  // PPAPI_UTILITY_THREADING_SIMPLE_THREAD_H_
     68 
     69