首页 > 解决方案 > 在等待输入时每秒将输出消息循环到标准输出 - PTHREAD

问题描述

我正在使用线程。我有一个线程每 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;
}

非常感谢正确方向的任何一点。先感谢您!

标签: cmultithreadingpthreadsmutexfread

解决方案


在您的情况下,您必须同步两个线程的读写。在这种情况下,最简单的方法是使用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中获得一些知识


推荐阅读