I am creating my first graphics program in C, using Codeblocks. I am trying to run two graphics loops simultaneously using two threads. One is for keyboard controls and the other is to move a rectangle vertically.
I have been trying to pass a graphics command from ObstacleHandler to the graphics window that main opens, using this condensed bit of code. When I run it, it will just crash as soon as it tries to draw the rectangle. If I initalise a window from the ObstacleHandler and then draw the rectangle, it will be fine. However, I need ObstacleHandler to draw the rectangle in the window that is initalised by the main.
Working example of the issue:
#include <pthread.h>
#include <semaphore.h>
#define NUM_THREADS 2
void *ObstacleHandler(void *threadid)
{
filled_rectangle(100, 120, 100, 120);
update_display();
pthread_exit(NULL);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
long t;
for(t=0;t<NUM_THREADS;t++)
{
printf("In main: creating thread %ld\n", t + 1);
}
pthread_create(&threads[1], NULL, ObstacleHandler, (void *)1);
initwindow(640, 480);
pthread_exit(NULL);
return 0;
}
The window has to be opened using the main function as the keyboard commands are in there. I cannot move them to the ObstacleHandler as that thread will be moving the obstacle.
Also, is there a way that you can have two graphics windows open and each one has a unique identification? I.e graph1 & graph2.
I am using allegro as the graphics library. However, not in the sample code.
I am new to programming so...! Any help would be appreciated!
Thanks
I use Borland/Embarcadero VCL so this could not be your case !!!
but my experience is that if you are accessing any Windows Visual stuff from different then owner window thread then somethings goes terribly wrong in the OS that creates:
this apply for any:
I code win32 apps and this behavior is present on XP/SP3 x86,W7 x86,W7 x64(WoW64). I did not test different OS versions but suspect this behavior is present also there ...
What to do?
create your global message que
just a list of command you want to support
threads will fill your que
just add appropriate command to que like: redraw window, draw line ...,add to log ...
main window will read and execute it
inside
OnTimer
orOnIdle
event[Notes]
If you use threads to enhance rendering speed then you should render to thread local bitmap instead and when done add command to copy its contents to target visual component. Do not forget that the que has to be thread safe so add locks to it !!!