Thread.cpp
1
2//
3// SFML - Simple and Fast Multimedia Library
4// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
5//
6// This software is provided 'as-is', without any express or implied warranty.
7// In no event will the authors be held liable for any damages arising from the use of this software.
8//
9// Permission is granted to anyone to use this software for any purpose,
10// including commercial applications, and to alter it and redistribute it freely,
11// subject to the following restrictions:
12//
13// 1. The origin of this software must not be misrepresented;
14// you must not claim that you wrote the original software.
15// If you use this software in a product, an acknowledgment
16// in the product documentation would be appreciated but is not required.
17//
18// 2. Altered source versions must be plainly marked as such,
19// and must not be misrepresented as being the original software.
20//
21// 3. This notice may not be removed or altered from any source distribution.
22//
24
26// Headers
28#include <SFML/System/Win32/Thread.hpp>
29#include <process.h>
30#include <iostream>
31
32
33namespace sf
34{
39myHandle (NULL),
40myFunction(NULL),
41myUserData(NULL)
42{
43
44}
45
46
50Thread::Thread(Thread::FuncType Function, void* UserData) :
51myHandle (NULL),
52myFunction(Function),
53myUserData(UserData)
54{
55
56}
57
58
63{
64 // Wait for the thread to finish before destroying the instance
65 Wait();
66}
67
68
73{
74 // Wait for the thread to finish, in case it was already running
75 Wait();
76
77 // Create the thread
78 myHandle = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, &Thread::ThreadFunc, this, 0, NULL));
79
80 // Error ?
81 if (myHandle == NULL)
82 std::cerr << "Failed to create thread" << std::endl;
83}
84
85
90{
91 if (myHandle)
92 {
93 // Wait for the thread to finish, no timeout
94 WaitForSingleObject(myHandle, INFINITE);
95
96 // Don't forget to close the thread handle (__endthreadex doesn't do it)
97 CloseHandle(myHandle);
98 myHandle = NULL;
99 }
100}
101
102
110{
111 if (myHandle)
112 {
113 TerminateThread(myHandle, 0);
114 myHandle = NULL;
115 }
116}
117
118
122void Thread::Run()
123{
124 if (myFunction)
125 myFunction(myUserData);
126}
127
128
132unsigned int __stdcall Thread::ThreadFunc(void* UserData)
133{
134 // The Thread instance is stored in the user data
135 Thread* ThreadInstance = reinterpret_cast<Thread*>(UserData);
136
137 // Forward to the instance
138 ThreadInstance->Run();
139
140 // Optional, but it is cleaner
141 _endthreadex(0);
142
143 return 0;
144}
145
146} // namespace sf
void Launch()
Create and run the thread.
Definition Thread.cpp:72
void Terminate()
Terminate the thread Terminating a thread with this function is not safe, you should rather try to ma...
Definition Thread.cpp:109
void Wait()
Wait until the thread finishes.
Definition Thread.cpp:89
Thread()
Default constructor.
Definition Thread.cpp:38
virtual ~Thread()
Virtual destructor.
Definition Thread.cpp:62