• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 Google Inc. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // Simple platform thread implementation used to test our cross-platform locks.
18 // This is a trimmed down version of Chromium base/threading/platform_thread.h.
19 
20 #ifndef SFNTLY_CPP_SRC_TEST_PLATFORM_THREAD_H_
21 #define SFNTLY_CPP_SRC_TEST_PLATFORM_THREAD_H_
22 
23 #if defined (WIN32)
24 #include <windows.h>
25 #else  // Assume pthread
26 #include <errno.h>
27 #include <pthread.h>
28 #include <time.h>
29 #endif // if defined (WIN32)
30 
31 #include "sfntly/port/type.h"
32 
33 namespace sfntly {
34 
35 #if defined (WIN32)
36 typedef HANDLE PlatformThreadHandle;
37 const PlatformThreadHandle kNullThreadHandle = NULL;
38 #else  // Assume pthread
39 typedef pthread_t PlatformThreadHandle;
40 const PlatformThreadHandle kNullThreadHandle = 0;
41 #endif
42 
43 class PlatformThread {
44  public:
45   class Delegate {
46    public:
~Delegate()47      virtual ~Delegate() {}
48      virtual void ThreadMain() = 0;
49   };
50 
51   // Sleeps for the specified duration (units are milliseconds).
52   static void Sleep(int32_t duration_ms);
53 
54   // Creates a new thread using default stack size.  Upon success,
55   // |*thread_handle| will be assigned a handle to the newly created thread,
56   // and |delegate|'s ThreadMain method will be executed on the newly created
57   // thread.
58   // NOTE: When you are done with the thread handle, you must call Join to
59   // release system resources associated with the thread.  You must ensure that
60   // the Delegate object outlives the thread.
61   static bool Create(Delegate* delegate, PlatformThreadHandle* thread_handle);
62 
63   // Joins with a thread created via the Create function.  This function blocks
64   // the caller until the designated thread exits.  This will invalidate
65   // |thread_handle|.
66   static void Join(PlatformThreadHandle thread_handle);
67 
68 private:
PlatformThread()69   PlatformThread() {}
70   NO_COPY_AND_ASSIGN(PlatformThread);
71 };
72 
73 }  // namespace sfntly
74 
75 #endif  // SFNTLY_CPP_SRC_TEST_PLATFORM_THREAD_H_
76