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 #include <process.h>
6 
7 /* thread proxy to user's thread proc */
8 #ifdef HOST_MINGW
9 static unsigned int WINAPI threadproc( void *param )
10 #else
11 static DWORD WINAPI threadproc( LPVOID param )
12 #endif
13 {
14  FBTHREAD *thread = param;
15 
16  /* call the user thread */
17  thread->proc( thread->param );
18 
19  /* free mem */
20  fb_TlsFreeCtxTb( );
21 
22  return 1;
23 }
24 
25 FBCALL FBTHREAD *fb_ThreadCreate( FB_THREADPROC proc, void *param, ssize_t stack_size )
26 {
27  FBTHREAD *thread = (FBTHREAD *)malloc( sizeof(FBTHREAD) );
28  if( thread == NULL )
29  return NULL;
30 
31  thread->proc = proc;
32  thread->param = param;
33 
34 #ifdef HOST_MINGW
35  /* Note: _beginthreadex()'s last parameter cannot be NULL,
36  or else the function fails on Windows 9x */
37  unsigned int thrdaddr;
38  thread->id = (HANDLE)_beginthreadex( NULL, stack_size, threadproc, (void *)thread, 0, &thrdaddr );
39 #else
40  DWORD dwThreadId;
41  thread->id = CreateThread( NULL, stack_size, threadproc, (void*)thread, 0, &dwThreadId );
42 #endif
43 
44  if( thread->id == NULL ) {
45  free( thread );
46  thread = NULL;
47  }
48 
49  return thread;
50 }
51 
53 {
54  if( thread == NULL )
55  return;
56 
57  WaitForSingleObject( thread->id, INFINITE );
58 
59  /* Never forget to close the threads handle ... otherwise we'll
60  * have "zombie" threads in the system ... */
61  CloseHandle( thread->id );
62 
63  free( thread );
64 }