【发布时间】: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