C - ncurses 和两个并发线程

标签 c concurrency pthreads screen ncurses

这个程序应该是运行两个并发线程的简单尝试,这两个线程都需要在同一屏幕上写入。

#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);
}

但一开始它甚至没有打印 hello 。怎么了?在这样一个带有两个线程的程序中如何处理一个独特的屏幕?

更新:在每个 printw 后放置 refresh(); 会产生以下输出

screen on



Thread 1

Thread 2

$

其中 $ 是提示符。因此,程序打印了字符串,但它(显然)随机地放置了一些意外的换行符,然后结束。它不应该,因为两个线程中都有 while(1) 指令!

最佳答案

正常配置中的curses/ncurses不支持线程,并且建议始终在单个线程中运行curses。自 ncurses 5.7 ,如果将库配置(编译时)为使用互斥体和其他入口点,则对线程应用程序已经有了基本的支持。

关于互斥体,几乎所有有关 POSIX 线程的教程都涵盖了这一点。这是一个示例:POSIX Threads Programming

关于C - ncurses 和两个并发线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060775/

相关文章:

c++ - C++中的线程安全队列

c - 我的函数和主要方法有什么问题?

c++ - 如何将#ifndef 与宏参数一起使用?

Scala 和 Java 内存模型

java - 为什么执行器不关闭?

java - 多线程环境中的 boolean 值

c - Linux:执行手动加载到内存的代码

c - 如何打印快速排序的中间结果并正确突出显示其枢轴元素

iphone - NSThread 有单独的堆吗? pthread 怎么样(在 iPhone 上)

c++ - pthread_kill() 与 pthread_cancel() 终止因 I/O 而阻塞的线程