The c language printf implements printing out instances at the same location
- 2020-05-30 20:52:15
- OfStack
The console prints at the same position as 1, for example: progress 1%- > 100% is displayed in the same position as 1. When I first learned the language c, I wanted to do it, but I couldn't check a lot of materials. After a gap of more than 6 years, I thought of this problem again in my spare time and decided to give it a try. Although the c language has almost been forgotten, hehe. Finally, it's done, this time lucky, haha! ^_^
#include <stdio.h>
#include <pthread.h>
//#include <sys/time.h>
//linux for sleep(seconds) and usleep(Microsecond)
//#include <unistd.h>
//windows for Sleep(millisecond)
//#include <windows.h>
// Create a thread function return type
pthread_t thread[1];
/**
* The thread function
**/
void *printThread(){
printf("%s\n"," The thread starts processing the task ");
printf(" It's been dealt with :");
for(int i = 1; i <= 100; i++) {
if(i==1){
// Number of 3 Lattice, % Account for 1 "
printf("%3d%%",i);
}else{
// refund 4 "
printf("\b\b\b\b%3d%%",i);
}
// Real time standard output ( Don't take \n , can't do without refreshing )
fflush(stdout);
// Time delay 1 seconds
sleep(1);
}
}
int main(){
printf(" I'm the main function oh, I'm creating a thread, hehe \n");
/* Create a thread */
if(pthread_create(&thread[0], NULL, printThread, NULL)!=0){
printf(" Thread creation failed \n");
}
printf(" Thread creation successful \n");
printf(" I am the main function. I am waiting for the thread to finish the task \n");
/* Waiting for the thread to end */
pthread_join(thread[0],NULL);
printf("\n The thread has ended \n");
return 1;
}
The code was successfully tested under mac os. The window system needs to introduce the pthread library into the compiler, and the multithreaded program based on pthread.h is developed by using Dev-C ++ under the reference example Windows