xref: /openssl/test/threadstest.h (revision 7ed6de99)
1 /*
2  * Copyright 2021-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #if defined(_WIN32)
11 # include <windows.h>
12 #endif
13 
14 #include <string.h>
15 #include "testutil.h"
16 
17 #if !defined(OPENSSL_THREADS) || defined(CRYPTO_TDEBUG)
18 
19 typedef unsigned int thread_t;
20 
run_thread(thread_t * t,void (* f)(void))21 static int run_thread(thread_t *t, void (*f)(void))
22 {
23     f();
24     return 1;
25 }
26 
wait_for_thread(thread_t thread)27 static int wait_for_thread(thread_t thread)
28 {
29     return 1;
30 }
31 
32 #elif defined(OPENSSL_SYS_WINDOWS)
33 
34 typedef HANDLE thread_t;
35 
thread_run(LPVOID arg)36 static DWORD WINAPI thread_run(LPVOID arg)
37 {
38     void (*f)(void);
39 
40     *(void **) (&f) = arg;
41 
42     f();
43     return 0;
44 }
45 
run_thread(thread_t * t,void (* f)(void))46 static int run_thread(thread_t *t, void (*f)(void))
47 {
48     *t = CreateThread(NULL, 0, thread_run, *(void **) &f, 0, NULL);
49     return *t != NULL;
50 }
51 
wait_for_thread(thread_t thread)52 static int wait_for_thread(thread_t thread)
53 {
54     return WaitForSingleObject(thread, INFINITE) == 0;
55 }
56 
57 #else
58 
59 typedef pthread_t thread_t;
60 
thread_run(void * arg)61 static void *thread_run(void *arg)
62 {
63     void (*f)(void);
64 
65     *(void **) (&f) = arg;
66 
67     f();
68     OPENSSL_thread_stop();
69     return NULL;
70 }
71 
run_thread(thread_t * t,void (* f)(void))72 static int run_thread(thread_t *t, void (*f)(void))
73 {
74     return pthread_create(t, NULL, thread_run, *(void **) &f) == 0;
75 }
76 
wait_for_thread(thread_t thread)77 static int wait_for_thread(thread_t thread)
78 {
79     return pthread_join(thread, NULL) == 0;
80 }
81 
82 #endif
83 
84