130efed1b5f4ec80cf3304ed7aeaee5518ed32f3
[yaz-moved-to-github.git] / src / thread_create.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2010 Index Data
3  * See the file LICENSE for details.
4  */
5
6 /**
7  * \file thread_create.c
8  * \brief Implements thread creation wrappers
9  *
10  */
11 #if HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #include <assert.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <stddef.h>
20 #include <yaz/xmalloc.h>
21 #include <yaz/log.h>
22 #include <yaz/thread_create.h>
23
24 #if YAZ_POSIX_THREADS
25 #include <pthread.h>
26 #endif
27 #ifdef WIN32
28 #include <windows.h>
29 #endif
30
31 struct yaz_thread {
32 #if YAZ_POSIX_THREADS
33     pthread_t id;
34 #else
35     void *return_data;
36 #ifdef WIN32
37     HANDLE id;
38 #endif
39 #endif
40 };
41
42 yaz_thread_t yaz_thread_create(void *(*start_routine)(void *p), void *arg)
43 {
44     yaz_thread_t t = xmalloc(sizeof(*t));
45 #if YAZ_POSIX_THREADS
46     int r = pthread_create(&t->id, 0, start_routine, arg);
47     if (r)
48     {
49         xfree(t);
50         t = 0;
51     }
52 #else
53     t->return_data = start_routine(arg);
54 #endif
55     return t;
56 }
57
58 void yaz_thread_join(yaz_thread_t *tp, void **value_ptr)
59 {
60     if (*tp)
61     {
62 #ifdef YAZ_POSIX_THREADS
63         pthread_join((*tp)->id, value_ptr);
64 #else
65         if (value_ptr)
66             *value_ptr = (*tp)->return_data;
67 #endif
68         xfree(*tp);
69         *tp = 0;
70     }
71 }
72
73 void yaz_thread_detach(yaz_thread_t *tp)
74 {
75     if (*tp)
76     {
77 #ifdef YAZ_POSIX_THREADS
78         pthread_detach((*tp)->id);
79 #endif
80         xfree(*tp);
81         *tp = 0;
82     }
83 }
84
85 /*
86  * Local variables:
87  * c-basic-offset: 4
88  * c-file-style: "Stroustrup"
89  * indent-tabs-mode: nil
90  * End:
91  * vim: shiftwidth=4 tabstop=8 expandtab
92  */
93