//------------------------------------------------------------| // This example tries to show the use of pthreadss, | // it only runs on Linux, because of the pthread.h | // header file. | // | // It has many bugs, you can only run it in a terminal | // started in a X-session, otherwise it will crash, the main | // problem is that i commented the pthread_join line, and | // i made that because that line waitss for the thread to | // end, and in this example it wouldn't work, i'm almost | // sure that changing the attr attributes can make this | // run better, any way, i didn't find the solution, another | // problem is that the thread runs too fast, so it's | // difficult to apreciate well the moves of the character. | // So, if you think you can resolve those problems, please | // send me a mail, or just modify the code, but please, let | // know, 'cause i really want to learn the solution. | // | // Author: Juan Francisco Benavides Nanni. | // mail: elnanni@gmail.com | // URL: http://mmabj.tk | // date: 29/12/2005 | //------------------------------------------------------------| #include #include #include #include #define MAXWIDX 78 #define MAXWIDY 19 #define MIN 0 #define CENTER 10 #define gotoxy(x,y) printf("\x1B[%i;%iH",(y),(x)) #define clrscr() printf("\x1B[2J") #define UP 115 #define DOWN 120 #define LEFT 122 #define RIG 99 #define SALE 27 void mover(int *opc); int mygetch(); int main(){ pthread_t thread_ID; pthread_attr_t attr; int opc, last, x, y; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); pthread_setconcurrency(2); char car = '^'; opc = UP; y = CENTER; x = y * 4; while(1){ if(opc == SALE) break; clrscr(); switch(opc){ case UP: if(y > MIN) y -= 1; else y = MAXWIDY; car = '^'; break; case DOWN: if(y < MAXWIDY) y += 1; else y = MIN; car = 'v'; break; case LEFT: if(x > MIN) x -= 1; else x = MAXWIDX; car = '<'; break; case RIG: if(x < MAXWIDX) x += 1; else x = MIN; car = '>'; break; case SALE: break; default: opc = last; } gotoxy(x, y); printf("%c", car); last = opc; pthread_create(&thread_ID, &attr, (void *) mover, &opc); //pthread_join(thread_ID, NULL); } } void mover(int *opc){ *opc = mygetch(); } int mygetch(){ struct termios oldt, newt; int ch; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); return ch; }