FreeBASIC  0.91.0
thread_core.c
Go to the documentation of this file.
1 /* thread creation and destruction functions */
2 
3 #include "../fb.h"
4 #include "../fb_private_thread.h"
5 
6 /* thread proxy to user's thread proc */
7 static void *threadproc( void *param )
8 {
9  FBTHREAD *thread = param;
10 
11  /* call the user thread */
12  thread->proc( thread->param );
13 
14  /* free mem */
15  fb_TlsFreeCtxTb( );
16 
17  /* don't return NULL or exit() will be called */
18  return (void *)1;
19 }
20 
21 FBCALL FBTHREAD *fb_ThreadCreate( FB_THREADPROC proc, void *param, ssize_t stack_size )
22 {
24  pthread_attr_t tattr;
25 
26  thread = (FBTHREAD *)malloc( sizeof(FBTHREAD) );
27  if( !thread )
28  return NULL;
29 
30  thread->proc = proc;
31  thread->param = param;
32 
33  if( pthread_attr_init( &tattr ) ) {
34  free( thread );
35  return NULL;
36  }
37 
38  /* Solaris pthread.h does not define PTHREAD_STACK_MIN */
39 #ifdef PTHREAD_STACK_MIN
40  stack_size = stack_size >= PTHREAD_STACK_MIN ? stack_size : PTHREAD_STACK_MIN;
41 #endif
42 
43  pthread_attr_setstacksize( &tattr, stack_size );
44 
45  if( pthread_create( &thread->id, &tattr, threadproc, (void *)thread ) ) {
46  free( (void *)thread );
47  return NULL;
48  }
49 
50  return thread;
51 }
52 
54 {
55  if( thread == NULL )
56  return;
57 
58  pthread_join( thread->id, NULL );
59 
60  free( thread );
61 }