Allegro Tutorial: Threading
Here is a link to threading in Linux. That will be very interesting as my Linux skills are still fairly limited at this point! But in the meantime I conned this Windows example of threading from my good friend and Linux guru Chris Martin. I figured if I didn’t post a copy of it here in my blog I would forget about it and give myself a big headache later trying to remember how it works. Here’s an example on how to start two threads in Allegro on Windows.
Include the following headers into your project.
#include <process.h> #include <allegro.h> #include <winalleg.h>
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.
#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 ); } }
This is why Linux/Unix > windows
I would have to agree with you there!