【问题标题】:C - ncurses and two concurrent threadsC - ncurses 和两个并发线程
【发布时间】:2015-11-10 16:52:40
【问题描述】:

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

#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) 指令!

【问题讨论】:

  • 在每个printw之后尝试refresh()

标签: c concurrency pthreads screen ncurses


【解决方案1】:
正常配置中的

curses/ncurses 不支持线程,对于 that 的建议一直是在单个线程中运行 curses。自 ncurses 5.7 以来,如果库被配置(编译时)使用互斥锁和其他入口点,则对线程应用程序的基本支持。

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

【讨论】:

  • 谢谢。在哪里可以找到有关互斥锁的更多文档?
  • 如果您对互斥锁(互斥锁)一无所知,则不应使用线程。该链接是一个很好的起点。
【解决方案2】:

它没有打印hello 字符串,但它被指令initscr() 快速清除:

initscr 代码确定终端类型并初始化所有 诅咒数据结构。 initscr 还会导致第一次调用刷新 清除屏幕。如果发生错误,initscr 会写一个适当的 标准错误的错误信息并退出;否则,指针是 返回stdscr。

printw 正在按预期打印,因为您没有刷新。您应该在每个printw 之后使用refresh()

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

【讨论】:

  • 谢谢,它很有用,但程序似乎仍然无法正常运行。我已更新我的问题以显示其新行为。
猜你喜欢
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多