Objective
Recently began my thread learning, a slight gain, compared with the process, its multi-threaded simultaneous execution of the code segment features, it is a huge charm.
Stealing that programming learning, such as martial arts training, learning moves but two strokes really should not, so do a dozen letters, practice.
Main ideas
The most important place to play the letter function is "the letter keeps falling, if the corresponding key is pressed, the letter disappears, and a new letter appears above, repeat this process".
In short, it is the need to accept user keys in real time when outputting information to the screen , which is in conflict with the sequence of programming we learned earlier, but threads can solve this problem.
Process Brief
- Close the input buffer and enter the echo.
- Create a global variable, save the character to be displayed, and its coordinate position.
Initializes the string, assigns it a random number, and assigns a value to its coordinates.
- Create a new thread, the function of the thread corresponding function for the clear screen after the output characters in their respective coordinates and after each loop, give the x-coordinate value of each of the sub-characters plus a
- In the original thread also set a loop, real-time receive user input, according to user input to determine whether the key is correct, if correct, re-assign the character randomly, otherwise re-enter.
- Real-time judgment, if there are letters over the lower bounds, if any, then the program ends
- Input buffers and input echo
Code
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>#include <time.h>Charstr[Ten];Charx[Ten];Chary[Ten];int* Thread () {intI while(1) {System ("Clear"); for(i=0;i<Ten; i++) {//output character at corresponding coordinates printf("\033[%d;%dh%c\n", X[i],y[i],str[i]); x[i]++; } Sleep (1); }returnNULL;}intMain () {pthread_t thid;intICharC=' + '; System"Stty-icanon"); System"Stty-echo"); Srand ((unsigned) time (NULL)); for(i=0;i<Ten; i++) {//String initializationStr[i] =' A '+ rand ()% -; X[i] =2; Y[i] = i*3+3; }//Create thread if(Pthread_create (&thid,null, (void*) Thread, (void*) &i)! =0) {printf("error!\n");Exit(1); } while(1) {c = GetChar ();if(c!=' + ') { for(i=0;i<Ten; i++) {if(c = = Str[i]) {Str[i] =' A '+rand ()% -; X[i] =2; C=' + '; Break; } } } for(i=0;i<Ten; i++) {if(x[i]>= -) { Break; }}} System ("Stty Icanonon"); System"Stty echo");return 0;}
Conclusion
Because the main purpose is to learn the thread, so the basic function of the alphabet can not be implemented after the implementation of other functions.
After all, is a beginner, what is wrong, welcome criticism.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The realization of the Cheng of the Linux line play the alphabet function