【发布时间】:2011-12-06 02:53:36
【问题描述】:
我有一个项目使用 curses 和套接字来制作一个会说话的程序。基本上主线程启动两个线程来管理屏幕的两半,另一个线程来管理通过网络的发送/接收。代码看起来很干净,但出于某种原因,光标有时会在屏幕上随机跳跃。通常它大约三排会开始在整个地方跳跃。我没有来自 curses 的 mv___() 函数,所以我很困惑为什么光标对我来说是流氓。
这里是两个线程调用来管理屏幕两侧的函数。关于可能导致此问题的任何想法?
void *display(int sub)
{
int bufSize = 10;
char* buf = (char*)calloc(bufSize, sizeof(char));
while(read(displayPipe[sub][0], buf, 1) > 0)
{
sem_wait(&displaySem);
waddch(subWin[sub], buf[0]);
wrefresh(subWin[sub]);
sem_post(&displaySem);
}
free(buf);
return NULL;
}
这是从套接字读取的函数
void *netToPipe()
{
int bufSize = 10;
char* buf = (char*)calloc(bufSize, sizeof(char));
// read from talkfd
while(read(talkfd, buf, 1) != EOF)
{
// print to the bottom of the screen
if(write(displayPipe[1][1], buf, 1) < 0)
(void)printf("Error writing to talkfd\n");
}
free(buf);
return NULL;
}
这里是 main() 的结尾,它从键盘读取并写入屏幕底部(通过管道)和套接字。
while(1)
{
// get a key from the subwindow
key = wgetch(subWin[0]);
// we are connected to a client
if(talkfd > 0)
{
// send across network
write(talkfd, &key, 1);
// copy to upper portion of the screen
write(displayPipe[0][1], &key, 1);
}
// we are just talking to self
else
{
// send to bottom of screen
write(displayPipe[1][1], &key, 1);
// send to top of screen
write(displayPipe[0][1], &key, 1);
}
refresh();
}
【问题讨论】:
-
@sarnold 我在这里只包括安装在我们的 linux 机器上的 curses.h 头文件。我不确定或不知道curses的线程感知版本。
-
请注意C99 introduced Variable Length Arrays——如果您的项目要求 C99 没问题,您可以将
calloc()替换为:char buf[bufSize];。 -
人力资源管理;我在packages.ubuntu.com 或packages.debian.org 或software.opensuse.org/121/en-- 上没有找到任何
ncursest线程感知变体,这让我想知道是否有任何发行版分发了线程感知变体? -
你有同时使用多线程程序和ncurses吗?这听起来很麻烦。要么在一个进程中完成所有事情,要么使用两个进程和两个终端......多线程终端代码听起来很不对。
标签: c multithreading sockets semaphore