Debian Codegraph @

c/tests/thread.h

raw
1 #ifndef TESTS_THREAD_H
2 #define TESTS_THREAD_H
3
4 /*
5 * Licensed to the Apache Software Foundation (ASF) under one
6 * or more contributor license agreements. See the NOTICE file
7 * distributed with this work for additional information
8 * regarding copyright ownership. The ASF licenses this file
9 * to you under the Apache License, Version 2.0 (the
10 * "License"); you may not use this file except in compliance
11 * with the License. You may obtain a copy of the License at
12 *
13 * http://www.apache.org/licenses/LICENSE-2.0
14 *
15 * Unless required by applicable law or agreed to in writing,
16 * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 /* Simulate a subset of POSIX threads for windows */
23
24 #ifdef _WIN32
25
26 #include <windows.h>
27 #include <process.h>
28
29 typedef struct {
30 HANDLE handle;
31 void *(*func)(void *);
32 void *arg;
33 } pthread_t;
34
35 static unsigned __stdcall pthread_run(void *thr0) {
36 pthread_t *t = (pthread_t *) thr0;
37 t->func(t->arg);
38 return 0;
39 }
40
41 static int pthread_create(pthread_t *t, void *unused, void *(*f)(void *), void *arg) {
42 t->func = f;
43 t->arg = arg;
44 t->handle = (HANDLE) _beginthreadex(0, 0, &pthread_run, t, 0, 0);
45 if (t->handle) {
46 return 0;
47 }
48 return -1;
49 }
50
51 static int pthread_join(pthread_t t, void **unused) {
52 if (t.handle) {
53 WaitForSingleObject(t.handle, INFINITE);
54 CloseHandle(t.handle);
55 }
56 return 0;
57 }
58
59 typedef CRITICAL_SECTION pthread_mutex_t;
60 #define pthread_mutex_init(m, unused) InitializeCriticalSectionAndSpinCount(m, 4000)
61 #define pthread_mutex_destroy(m) DeleteCriticalSection(m)
62 #define pthread_mutex_lock(m) EnterCriticalSection(m)
63 #define pthread_mutex_unlock(m) LeaveCriticalSection(m)
64
65 void millisleep(long ms) { Sleep(ms); }
66
67 #else /* POSIX */
68
69 #include <pthread.h>
70 #include <unistd.h> /* For sleep() */
71
72 void millisleep(long ms) {
73 struct timespec delay = {0};
74 delay.tv_sec = ms / 1000;
75 delay.tv_nsec = (ms % 1000) * 1000000;
76 nanosleep(&delay, NULL);
77 }
78
79 #endif
80
81 #endif /*!TESTS_THREAD_H*/