1 mike 1.1 /*
2 **==============================================================================
3 **
4 ** Open Management Infrastructure (OMI)
5 **
6 ** Copyright (c) Microsoft Corporation
7 **
8 ** Licensed under the Apache License, Version 2.0 (the "License"); you may not
9 ** use this file except in compliance with the License. You may obtain a copy
10 ** of the License at
11 **
12 ** http://www.apache.org/licenses/LICENSE-2.0
13 **
14 ** THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 ** KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
16 ** WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
17 ** MERCHANTABLITY OR NON-INFRINGEMENT.
18 **
19 ** See the Apache 2 License for the specific language governing permissions
20 ** and limitations under the License.
21 **
22 mike 1.1 **==============================================================================
23 */
24
25 #include "thread.h"
26
27 #if defined(CONFIG_OS_WINDOWS)
28 # include <time.h>
29 #else
30 # include <unistd.h>
31 # include <sys/time.h>
32 # include <sys/types.h>
33 # include <pthread.h>
34 #endif
35
36 /* creates a thread; returns a handle.
37 each successful 'create-thread' has to be followed by 'close-thread-handle' */
38 MI_Result Thread_Create(
39 ThreadProc proc,
40 void* proc_param,
41 ThreadHandle* selfOut)
42 {
43 mike 1.1 MI_Result r = MI_RESULT_OK;
44 #if defined(CONFIG_OS_WINDOWS)
45 HANDLE h = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)(proc), proc_param, 0, 0);
46
47 if (h != NULL)
48 {
49 r = MI_RESULT_OK;
50 *selfOut = GetThreadId(h);
51 CloseHandle(h);
52 }
53 else
54 {
55 r = MI_RESULT_FAILED;
56 }
57 #else
58 r = (0 == pthread_create(selfOut, NULL, proc, proc_param)) ? MI_RESULT_OK : MI_RESULT_FAILED;
59 #endif
60 return r;
61 }
62
63 /* closes thread handle and frees related system resources;
64 mike 1.1 optionally, may wait for thread to complete */
65 MI_Result Thread_Destroy(
66 ThreadHandle self,
67 MI_Boolean wait )
68 {
69 MI_Result r = MI_RESULT_OK;
70 #if defined(CONFIG_OS_WINDOWS)
71 if (wait)
72 {
73 HANDLE h = OpenThread( SYNCHRONIZE, FALSE, self);
74 if (h != NULL)
75 {
76 DWORD res = WaitForSingleObject(h, INFINITE);
77 r = (WAIT_OBJECT_0 == res) ? MI_RESULT_OK : MI_RESULT_FAILED;
78 CloseHandle(h);
79 }
80 else
81 r = MI_RESULT_OK;
82 }
83 #else
84 if (wait)
85 mike 1.1 pthread_join(self, 0);
86 else
87 pthread_detach(self);
88 #endif
89 return r;
90 }
91
92 /* returns ID of the current thread */
93 ThreadHandle ThreadSelf()
94 {
95 #if defined(CONFIG_OS_WINDOWS)
96 return GetCurrentThreadId();
97 #else
98 return pthread_self();
99 #endif
100 }
101
|