BowPark
BowPark

Reputation: 1460

C - ncurses and two concurrent threads

This program should be a trivial attempt to run two concurrent threads which both need to write on the same screen.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <pthread.h>
#include <ncurses.h>

void *function1(void *arg1);
void *function2(void *arg2);

int main(int argc, char *argv[])
{
    printf("hello");

    initscr();
    printw("screen on\n");

    pthread_t function1t;
    pthread_t function2t;

    if( pthread_create( &function1t, NULL, function1, NULL) < 0)
    {
    printw("could not create thread 1");
    return 1;
    }

    if( pthread_create( &function2t, NULL, function2, NULL) < 0)
    {
    printw("could not create thread 2");
    return 1;
    }

    endwin();
    return 0;
}

void *function1(void *arg1)
{
    printw("Thread 1\n");
    while(1);
}

void *function2(void *arg2)
{
    printw("Thread 2\n");
    while(1);
}

But it doesn't even print hello in the beginning. What's wrong? How can a unique screen be handled in such a program, with two threads?

Update: putting a refresh(); after each printw produces the following output

screen on



Thread 1

Thread 2

$

Where $ is the prompt. So, the program prints the string, but it puts (apparently) randomly some unexpected newlines and it ends. It shouldn’t, due to the while(1) instructions in both the threads!

Upvotes: 2

Views: 4003

Answers (2)

Assem
Assem

Reputation: 12077

It is not printing the hello string but it's quickly cleared with the instruction initscr():

The initscr code determines the terminal type and initializes all curses data structures. initscr also causes the first call to refresh to clear the screen. If errors occur, initscr writes an appropriate error message to standard error and exits; otherwise, a pointer is returned to stdscr.

printw is printing as expected because you are not refreshing. You should use refresh() after each printw:

printw("screen on\n");
refresh();

Upvotes: 1

Thomas Dickey
Thomas Dickey

Reputation: 54505

curses/ncurses in the normal configuration does not support threads, and the recommendation for that has always been to run curses in a single thread. Since ncurses 5.7, there has been rudimentary support for threaded applications if the library is configured (compile-time) to use mutexes and additional entrypoints.

Regarding mutexes, almost any tutorial on POSIX threads covers that. Here is an example: POSIX Threads Programming

Upvotes: 1

Related Questions