简体   繁体   中英

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. The code below executes fine however every time the character a is typed in the output is tabbed in the terminal.

I compiled with 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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