Moved util routines for BeOS from Unix, instead of using them
[silc.git] / lib / silcutil / beos / silcbeosthread.c
1 /*
2
3   silcbeosthread.c 
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2002 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /* I used Apache's APR code as a reference here. */
20 /* $Id$ */
21
22 #include "silcincludes.h"
23
24 #ifdef SILC_THREADS
25
26 /* Thread structure for BeOS */
27 typedef struct {
28   thread_id thread;
29   SilcThreadStart start_func;
30   void *context;
31   bool waitable;
32 } *SilcBeosThread;
33
34 /* Actual routine that is called by BeOS when the thread is created.
35    We will call the start_func from here. */
36
37 static void *silc_thread_beos_start(void *context)
38 {
39   SilcBeosThread thread = (SilcBeosThread)context;
40   return (*thread->start_func)(thread->context);
41 }
42
43 #endif
44
45 SilcThread silc_thread_create(SilcThreadStart start_func, void *context,
46                               bool waitable)
47 {
48 #ifdef SILC_THREADS
49   int ret;
50   SilcBeosThread thread = silc_calloc(1, sizeof(*thread));
51   if (!thread)
52     return NULL;
53
54   thread->start_func = start_func;
55   thread->context = context;
56   thread->waitable = waitable;
57
58   /* Create the thread, and run it */
59   thread->thread = spawn_thread((thread_func)silc_thread_beos_start,
60                                 B_NORMAL_PRIORITY, thread);
61   ret = resume_thread(thread->thread);
62   if (ret < B_NO_ERROR) {
63     SILC_LOG_ERROR(("Could not create new thread"));
64     silc_free(thread);
65     return NULL;
66   }
67
68   return (SilcThread)thread->thread;
69 #else
70   /* Call thread callback immediately */
71   (*start_func)(context);
72   return NULL;
73 #endif
74 }
75
76 void silc_thread_exit(void *exit_value)
77 {
78 #ifdef SILC_THREADS
79   exit_thread((status_t)exit_value);
80 #endif
81 }
82
83 SilcThread silc_thread_self(void)
84 {
85 #ifdef SILC_THREADS
86   return (SilcThread)find_thread(NULL);
87 #else
88   return NULL;
89 #endif
90 }
91
92 bool silc_thread_wait(SilcThread thread, void **exit_value)
93 {
94 #ifdef SILC_THREADS
95   status_t ret, retval;
96
97   ret = wait_for_thread((thread_id)thread, &retval);
98   if (ret == B_NO_ERROR) {
99     if (exit_value)
100       *exit_value = retval;
101     return TRUE;
102   }
103
104   return FALSE;
105 #else
106   return FALSE;
107 #endif
108 }