Windows Threading and Allegro
From MWCSWiki
Windows Threading and Allegro
There is an easier solution to using threading than using pthreads. So lets get started using windows threads.
First you must include the following headers into your project. <pre>
- include <process.h>
- include <allegro.h>
- include <winalleg.h>
</pre>
These headers must be included in the exact order that they appear here.
The winalleg.h header file allows the use of most functions and types defined in
the windows.h header for the win32 API and it must be included only after
including the allegro.h header.
Once these headers are included in your project, you may begin to work with threading.
I will provide a simple example to demonstrate how easy this is. You may cut and paste
this text directly from the wiki and have it work for you with Dev-C++.
<pre>
- include <process.h>
- include <allegro.h>
- include <winalleg.h>
void init( void ); void deinit( void );
/* thread callback functions */
void ThreadOne( void* data ); void ThreadTwo( void* data );
/* Mutex */
HANDLE hMutex;
int main( void ) {
/* handle the initialization of allegro lib */
init();
/* create the mutex to lock and unlock resources
* for each thread.
*/
hMutex = CreateMutex( NULL, FALSE, NULL );
/* start both threads */
_beginthread( ThreadOne, 0, NULL );
_beginthread( ThreadTwo, 0, NULL );
/* start main application loop */
while( !key[KEY_ESC] )
{
WaitForSingleObject( hMutex, INFINITE );
textprintf_centre_ex( screen, font, SCREEN_W/2, 400, 0xffffff, -1,
"Hello World from Main!!!" );
ReleaseMutex( hMutex );
}
/* cleanup after allegro lib */
deinit();
/* return success or zero to OS */
return 0;
} END_OF_MAIN()
void init( void ) {
int depth, res;
allegro_init();
depth = desktop_color_depth();
if( depth == 0 )
depth = 32;
set_color_depth( depth );
res = set_gfx_mode( GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0 );
if( res != 0 )
{
allegro_message( allegro_error );
exit( -1 );
}
install_keyboard();
}
void deinit( void ) {
clear_keybuf();
}
void ThreadOne( void* data ) {
int i = 0;
bool done = false;
/* run loop until we are done, just to show that the thread loop doesn't affect
* the main loop.
*/
while( !done )
{
/* lock or wait for the mutex to be free before we write */
WaitForSingleObject( hMutex, INFINITE );
textprintf_ex( screen, font, 0, 50 + i, 0xffffff, -1, "Hello World from ThreadOne!!!" );
if( i == 100 )
done = true;
else
i += 10;
/* for right now we are done using the mutex, so release it */
ReleaseMutex( hMutex );
}
}
void ThreadTwo( void* data ) {
int i = 0;
bool done = false;
while( !done )
{
WaitForSingleObject( hMutex, INFINITE );
textprintf_ex( screen, font, 200, 50 + i, 0x00ff00, -1, "Hello World from ThreadTwo!!!" );
if( i == 200 )
done = true;
else
i += 10;
ReleaseMutex( hMutex );
}
}
</pre>

