Imported Upstream version 1.4
[deb_x265.git] / source / common / threading.cpp
CommitLineData
72b9787e
JB
1/*****************************************************************************
2 * x265: threading class and intrinsics
3 *****************************************************************************
4 * Copyright (C) 2013 x265 project
5 *
6 * Authors: Steve Borho <steve@borho.org>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
21 *
22 * This program is also available under a commercial proprietary license.
23 * For more information, contact us at license @ x265.com
24 *****************************************************************************/
25
26#include "threading.h"
27
28namespace x265 {
29// x265 private namespace
30
31/* C shim for forced stack alignment */
32static void stackAlignMain(Thread *instance)
33{
34 instance->threadMain();
35}
36
37#if _WIN32
38
39static DWORD WINAPI ThreadShim(Thread *instance)
40{
41 // defer processing to the virtual function implemented in the derived class
42 x265_stack_align(stackAlignMain, instance);
43
44 return 0;
45}
46
47bool Thread::start()
48{
49 DWORD threadId;
50
51 this->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadShim, this, 0, &threadId);
52
53 return threadId > 0;
54}
55
56void Thread::stop()
57{
58 if (this->thread)
59 WaitForSingleObject(this->thread, INFINITE);
60}
61
62Thread::~Thread()
63{
64 if (this->thread)
65 CloseHandle(this->thread);
66}
67
68#else /* POSIX / pthreads */
69
70static void *ThreadShim(void *opaque)
71{
72 // defer processing to the virtual function implemented in the derived class
73 Thread *instance = reinterpret_cast<Thread *>(opaque);
74
75 x265_stack_align(stackAlignMain, instance);
76
77 return NULL;
78}
79
80bool Thread::start()
81{
82 if (pthread_create(&this->thread, NULL, ThreadShim, this))
83 {
84 this->thread = 0;
85
86 return false;
87 }
88
89 return true;
90}
91
92void Thread::stop()
93{
94 if (this->thread)
95 pthread_join(this->thread, NULL);
96}
97
98Thread::~Thread() {}
99
100#endif // if _WIN32
101
102Thread::Thread()
103{
104 this->thread = 0;
105}
106}