【问题标题】:loop output message into standard output every second while waiting for input - PTHREAD在等待输入时每秒将输出消息循环到标准输出 - PTHREAD
【发布时间】:2020-04-03 10:57:04
【问题描述】:

我正在处理线程。我有一个线程每 a1 秒输出到标准输出“等待......”。我试图在我的主线程中的标准输入中写入一些东西,但是当“等待......”输出发生时,它会吸收我到目前为止能够写的字母。 我真的很困惑。我假设我只需要在标准输入中检测到换行符时才需要输出,但我不知道如何检查。

它提供给我的输出:

waiting ...
waiting ...
fri <-- me trying to input friends 
friwaiting ... <-- fri gets sucked in halfway through me typing it
waiting ...
waiting ...

我的代码:

void* thread_one(void* arg){

    while(1){
        sleep(1);
        if (write(1, "waiting ...\n", 12) != 12) {
            write(2, "There was an error writing to standard out\n", 44);
        }
    }
    return NULL;
}

int main(int argc, char **argv){
    char buffer[11];
    pthread_t tid;
    pthread_create(&tid, NULL, thread_one, NULL);

    while(1){
        int r = read(0, buffer, 10);
        if(r<=0){
            break;
        }
        buffer[r] = 0;
        printf("message: %s\n", buffer);

        if(strcmp(buffer, "exit\n")==0){
            break;
        }

    }

    return 0;
}

非常感谢任何正确方向的观点。提前谢谢!

【问题讨论】:

    标签: c multithreading pthreads mutex fread


    【解决方案1】:

    在您的情况下,您必须同步两个线程的读写。在这种情况下,最简单的是使用mutex。可以看下面的代码:

    #include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h>
    #include <pthread.h>
    #include <time.h>
    #include <unistd.h>
    
    // using the mutex "lock"
    pthread_mutex_t lock;
    void* thread_one(void* arg){
    
        while(1){
            sleep(1);
            // lock the mutex
            pthread_mutex_lock(&lock);
            if (write(1, "waiting ...\n", 12) != 12) {
                write(2, "There was an error writing to standard out\n", 44);
            }
            // unlock the mutex after writing
            pthread_mutex_unlock(&lock);
        }
        return NULL;
    }
    
    int main(int argc, char **argv){
        char buffer[11];
        pthread_t tid;
       pthread_mutex_init(&lock], NULL);
        pthread_create(&tid, NULL, thread_one, NULL);
    
        while(1){
            // lock mutex to read
            pthread_mutex_lock(&lock);
            int r = read(0, buffer, 10);
            // unlock after reading
            pthread_mutex_unlock(&lock);
            if(r<=0){
                break;
            }
            buffer[r] = 0;
            printf("message: %s\n", buffer);
    
            if(strcmp(buffer, "exit\n")==0){
                break;
            }
    
        }
    
        return 0;
    }
    

    输出:

    waiting ...
    message: friday
    
    monday
    message: monday
    
    waiting ...
    

    你也可以在本教程中有所了解pthread

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多