簡體   English   中英

多線程正在寫入輸出選項卡

[英]Multi-threading is writing outputted tabbed

我正在處理涉及使用ncurses.h操作系統任務的一部分,我遇到了一個奇怪的問題。 下面的代碼執行得很好,但是每次在輸出中輸入字符a都會在終端中進行選項卡。

我用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);
    }
}

輸出如下所示:

aFERN
 aFERN
      aFERN
           aFERN
                aFERN
                     aFERN
                          aFERN
                               bbccaFERN
                                        aFERN

你最好在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);
    }
}

輸出正常:

aFERN
aFERN
aFERN
aFERN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM