The objective is to make workin()
a low priority thread while other really heavy calculations are being made.
Is there a way to make a wait()
of, lets say, 0.5 seconds?
Is it possible to block incoming characters to terminal while on wait()
? because it messes up with the characters printed to "processing ... " this part is solved, see solution below
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *workin(){
int i=0,count=10;
char v[]={' ',' ','-','-','-',' ',' ',' ',' ',' '};
for(;;){
for(i=count-1;i>=0;i--){
v[(i+1)%(count)]=v[i];
}
fflush(stdout);
printf("\r");
printf("processing ");
printf("%s ",v);
sleep(1);
}
}
int main(int argc, char *argv[]){
pthread_t tid;
pthread_create(&tid,NULL,workin,NULL);
sleep(15);/*HEAVY stuff here*/
pthread_cancel(tid);
printf("\r\n");
return 0;
}
Half solved, missing wait(0.5)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
char getch(){
/*#include <unistd.h> //_getch*/
/*#include <termios.h> //_getch*/
char buf=0;
struct termios old = {0};
fflush(stdout);
if(tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag&=~ICANON;
old.c_lflag&=~ECHO;
old.c_cc[VMIN]=1;
old.c_cc[VTIME]=0;
if(tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if(read(0,&buf,1)<0)
perror("read()");
old.c_lflag|=ICANON;
old.c_lflag|=ECHO;
if(tcsetattr(0, TCSADRAIN, &old) < 0)
perror ("tcsetattr ~ICANON");
return buf;
}
void *workin(){
int i=0,count=10;
char v[]={' ',' ','>','>','>',' ',' ',' ',' ',' '};
for(;;){
for(i=count-1;i>=0;i--){
v[(i+1)%(count)]=v[i];
}
fflush(stdout);
printf("processing ");
printf("%s ",v);
printf("\r");
sleep(1);
}
}
int main(int argc, char *argv[]){
char ch=0;
pthread_t tid;
pthread_create(&tid,NULL,workin,NULL);
do{
ch=getch();/*HEAVY CALCULATIONS HERE*/
}while(1);
pthread_cancel(tid);
printf("\r\n");
return 0;
}
一种方法是将特定的线程输出传递到终端(手动打开),就像写入文件内容一样
The way I have learned to "flush" stdin
is to read from it and discard the information.
The way I have found to do a wait()
of half a second (0.5s) is using:
#define _XOPEN_SOURCE 600
usleep(500000);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.