我正在使用 ncurses 在 C 中编写基于文本的客户端。程序的主循环只是阻塞,直到检测到按键,然后处理它并继续等待另一个按键。
我启动了一个线程(在下面发布),它阻塞(使用 select)等待来自服务器的输入,当它接收到它时,它会将其添加到聊天日志缓冲区并将缓冲区打印到屏幕上。它完美地工作。
我知道 ncurses 不是线程安全的,但我对线程的理解是,只要我 100% 确定一次只有一个线程调用 ncurses,它就可以正常工作。
我的问题是光标位置。
它是用该行修改的,move(height+1, curx);
无论我传递给它什么值,ncurses 似乎完全忽略了调用并将我的光标放在不同的位置。我似乎无法影响它。
为了进一步解释这个问题,在我的主线程(按键循环)中,我使用了相同的互斥锁。当光标在这些代码部分中更新时,它会按计划工作。当它从下面的接收线程更新时,游标调用被忽略。
有任何想法吗?
receive thread
char buf[512];
fd_set read_fds;
FD_ZERO(&read_fds);
int nbytes;
for (;;) {
read_fds = master;
select(sockfd+1, &read_fds, NULL, NULL, NULL);
pthread_mutex_lock(&mutexdisplay);
memset(&buf, 0, sizeof buf);
nbytes = recv(sockfd, buf, 512, 0);
buf[nbytes] = 0;
add_chatmsg(chatlog, &numchatlog, buf);
// erase window
werase(chat_window);
// redraw border
wborder(chat_window, '|', '|', '-', '-', '+', '+', '+', '+');
// scroll completely into the future
chatlogstart = numchatlog-1;
// print the chat log
print_chatlog(chatlog, &numchatlog, &chatlogstart, &height);
move(height+1, curx);
// refresh window
wrefresh(chat_box);
wrefresh(chat_window);
pthread_mutex_unlock(&mutexdisplay);
}