简体   繁体   English

多线程正在写入输出选项卡

[英]Multi-threading is writing outputted tabbed

I'm working on part of my OS assignment which involves using ncurses.h , I've come across a strange problem.我正在处理涉及使用ncurses.h操作系统任务的一部分,我遇到了一个奇怪的问题。 The code below executes fine however every time the character a is typed in the output is tabbed in the terminal.下面的代码执行得很好,但是每次在输出中输入字符a都会在终端中进行选项卡。

I compiled with clang -Wall -lpthread -lncurses test.c我用clang -Wall -lpthread -lncurses test.c编译

#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

void move_character(char character);
void initialize_screen();

pthread_t attendees[50];
pthread_mutex_t lock;
static int curses_initialized = FALSE;

void* func(void* arg) {
    return NULL;
}

void initialize_screen() {
    assert(!curses_initialized);

    initscr();
    start_color();

    curses_initialized = TRUE;
}

int main(int argc, char** argv) {
    printf("HRE");
    char ch;

    pthread_create(&attendees[0], NULL, func, NULL);
    pthread_join(attendees[0], NULL);

    initialize_screen();

    while ((ch = getch()) != '`') {
        if (ch >= 'a' && ch <= 'z') {
            move_character(ch);
        }
    }
}

void move_character(char character) {
    // Multi-thread here
    // Check if thread is not already made (came from the file)

    if(attendees[character - 'a'] != NULL) {
        pthread_mutex_lock(&lock);
        printf("FERN\n");
        fflush(stdout);
        pthread_mutex_unlock(&lock);
    }
}

The output looks as follows:输出如下所示:

aFERN
 aFERN
      aFERN
           aFERN
                aFERN
                     aFERN
                          aFERN
                               bbccaFERN
                                        aFERN

You'd better using printw() instead of printf() in curses.你最好在curses 中使用printw()而不是printf()

void move_character(char character) {
    // Multi-thread here
    // Check if thread is not already made (came from the file)

    if(attendees[character - 'a'] != 0) {
        pthread_mutex_lock(&lock);
        printw("FERN\n");
//        fflush(stdout);
        pthread_mutex_unlock(&lock);
    }
}

and the output is ok :输出正常:

aFERN
aFERN
aFERN
aFERN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM