等(0.5)有办法吗? --fflush()阻止stdin?

时间:2013-05-09 09:12:42

标签: c input io pthreads wait

目标是使workin()成为低优先级线程,同时进行其他非常繁重的计算。

有没有办法制作wait(),比方说,0.5秒?

是否可以在wait()时阻止传入的字符到终端?因为它与打印到“处理......”的字符混淆了,这部分解决了,见下面的解决方案

#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;
}

一半已解决,缺少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;
}

2 个答案:

答案 0 :(得分:0)

一种方法是将特定线程输出传递给终端(手动打开),如写入文件内容

答案 1 :(得分:0)

我学会“冲洗”stdin的方法是从中读取并丢弃信息。

我发现做wait()半秒(0.5秒)的方式正在使用:

#define _XOPEN_SOURCE 600

usleep(500000);
相关问题