Initial commit - from Precise source
[freerdp-ubuntu-pcb-backport.git] / libfreerdp-utils / thread.c
1 /**
2  * FreeRDP: A Remote Desktop Protocol client.
3  * Thread Utils
4  *
5  * Copyright 2011 Vic Lee
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <time.h>
24
25 #ifdef _WIN32
26 #include <windows.h>
27 #ifdef _MSC_VER
28 #include <process.h>
29 #endif
30 #endif
31
32 #include <freerdp/utils/sleep.h>
33 #include <freerdp/utils/memory.h>
34 #include <freerdp/utils/thread.h>
35
36 freerdp_thread* freerdp_thread_new(void)
37 {
38         freerdp_thread* thread;
39
40         thread = xnew(freerdp_thread);
41         thread->mutex = freerdp_mutex_new();
42         thread->signals[0] = wait_obj_new();
43         thread->signals[1] = wait_obj_new();
44         thread->num_signals = 2;
45
46         return thread;
47 }
48
49 void freerdp_thread_start(freerdp_thread* thread, void* func, void* arg)
50 {
51         thread->status = 1;
52
53 #ifdef _WIN32
54         {
55 #       ifdef _MSC_VER
56                 CloseHandle((HANDLE)_beginthreadex(NULL, 0, func, arg, 0, NULL));
57 #else
58                 CloseHandle(CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, arg, 0, NULL));
59 #endif
60         }
61 #else
62         {
63                 pthread_t th;
64                 pthread_create(&th, 0, func, arg);
65                 pthread_detach(th);
66         }
67 #endif
68 }
69
70 void freerdp_thread_stop(freerdp_thread* thread)
71 {
72         int i = 0;
73
74         wait_obj_set(thread->signals[0]);
75
76         while (thread->status > 0 && i < 1000)
77         {
78                 i++;
79                 freerdp_usleep(100000);
80         }
81 }
82
83 void freerdp_thread_free(freerdp_thread* thread)
84 {
85         int i;
86
87         for (i = 0; i < thread->num_signals; i++)
88                 wait_obj_free(thread->signals[i]);
89         thread->num_signals = 0;
90
91         freerdp_mutex_free(thread->mutex);
92         thread->mutex = NULL;
93
94         xfree(thread);
95 }