ncurse界面编程多线程示例
生活随笔
收集整理的這篇文章主要介紹了
ncurse界面编程多线程示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
linux ncurses界面編程網上資料很多,這里不再詳述,這里只給一個例子。該示例給出了一個左右跳動的字符串數組景象:
//Compile: gcc -g ncurses_demo.c -o ncurses_demo -lpthread -lncurses
//Run: ./ncureses_demo 1 2 3 4 5 6 7 8 9 0
//Usage: q quit, 空白 全部反向, 0-9, 指定某行字符反向顯示
//#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <curses.h>
#include <pthread.h>
#include <unistd.h>#define MAXMSG 10 //最多允許用戶輸入的字符串個數,超過的部分會忽略, 也是創建的線程數
#define TUNIT 20000 //usleep函數休眠的時間因子struct propset
{char *str; //顯示的字符串int row; //行數, 一個線程對應一行int delay; //超時時間int dir; //方向, 向左或是向右
};int setup (int, char **, struct propset *);
void *animate (void *arg);pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;int main (int argc, char *argv[])
{int c;pthread_t thrds[MAXMSG];struct propset props[MAXMSG];int num_msg;int i;if (argc == 1){printf ("usage:%s string ...\n", argv[0]);exit (1);}num_msg = setup (argc - 1, argv + 1, props);for (i = 0; i < num_msg; i++){ //用戶輸入幾個字符串就創建幾個線程if (pthread_create (&thrds[i], NULL, animate, &props[i])){ //若成功創建線程會返回0fprintf (stderr, "error creating thread");endwin ();exit (0);}}while (1){c = getch ();if (c == 'Q' || c == 'q')break; //退出if (c == ' '){ //全部反向for (i = 0; i < num_msg; i++)props[i].dir = -props[i].dir;}if (c >= '0' && c <= '9'){ //指定某個字符串反向i = c - '0';if (i < num_msg)props[i].dir = -props[i].dir;}}pthread_mutex_lock (&mx); //上鎖,然后取消所有的線程for (i = 0; i < num_msg; i++)pthread_cancel (thrds[i]);endwin ();return 0;
}int setup (int nstring, char *strings[], struct propset props[])
{int num_msg = (nstring > MAXMSG ? MAXMSG : nstring); //限制輸入的字符串最大個數, 這里是10個int i;srand (getpid ());for (i = 0; i < num_msg; i++){props[i].str = strings[i];props[i].row = i;props[i].delay = 1 + (rand () % 15);props[i].dir = ((rand () % 2) ? 1 : -1);}initscr ();crmode ();noecho ();clear ();mvprintw (LINES - 1, 0, "'Q' to quit,'0'..'%d' to bounce", num_msg - 1); //在屏幕底端打印字條串return num_msg;
}void *animate (void *arg)
{struct propset *info = arg;int len = strlen (info->str) + 2; //+2 for paddingint col = rand () % (COLS - len - 3);while (1){usleep (info->delay * TUNIT);pthread_mutex_lock (&mx);move (info->row, col);addch (' ');addstr (info->str);addch (' ');move (LINES - 1, COLS - 1);refresh ();pthread_mutex_unlock (&mx);col += info->dir;if (col <= 0 && info->dir == -1)info->dir = 1;else if (col + len >= COLS && info->dir == 1)info->dir = -1;}
}
用法如下:
./ncurese_demo ?1 2 3 4 5 6 7 8 9 0
q ?退出, 空白鍵 全部反向, 0-9之一 ?指定某行字符反向顯示
運行截圖
參考文獻
[1].http://www.kuqin.com/cpluspluslib/20111226/316716.html
[2].http://www.cnblogs.com/Xiao_bird/archive/2009/07/21/1527947.html
總結
以上是生活随笔為你收集整理的ncurse界面编程多线程示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: libcurl 编程进度条和range请
- 下一篇: Ubuntu 14.04 64bit上c