Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <ncurses.h>
- #include <errno.h>
- #include <cstring>
- #define MAX_THREAD_NUMBER 10
- void* writer( void* );
- void removeAll();
- int addThread();
- int removeThread();
- pthread_mutex_t mu;
- int quitThread[MAX_THREAD_NUMBER];
- int currentThreadCount = 0;
- pthread_t handle[MAX_THREAD_NUMBER];
- void init()
- {
- initscr();
- clear();
- noecho();
- refresh();
- curs_set(0);
- pthread_mutex_init(&mu, NULL);
- }
- int main()
- {
- init();
- int isQuit = 0;
- while(isQuit == 0)
- {
- fflush(stdin);
- char c = getch();
- switch ( c )
- {
- case '+':
- addThread();
- break;
- case '-':
- removeThread();
- break;
- case 'q':
- isQuit = 1;
- break;
- default:
- break;
- }
- }
- removeAll();
- pthread_mutex_destroy(&mu);
- echo();
- endwin();
- return 0;
- }
- int removeThread()
- {
- if(currentThreadCount != 0)
- {
- quitThread[--currentThreadCount] = 1;
- if (pthread_join(handle[currentThreadCount], NULL) != 0)
- {
- printw("pthread_join(%lu) failed with error %s\n", handle[currentThreadCount] ,strerror(errno));
- refresh();
- }
- }
- return 0;
- }
- int addThread()
- {
- if ( currentThreadCount < MAX_THREAD_NUMBER)
- {
- quitThread[currentThreadCount] = 0;
- if (pthread_create(&handle[currentThreadCount], NULL, writer, (void*)currentThreadCount) != 0)
- {
- printw("pthread_create() failed with error %s\n", strerror(errno));
- refresh();
- return 1;
- }
- else
- {
- currentThreadCount++;
- }
- }
- return 0;
- }
- void removeAll()
- {
- while( currentThreadCount > 0 )
- {
- quitThread[--currentThreadCount] = 1;
- if (pthread_join(handle[currentThreadCount], 0) != 0)
- {
- printw("pthread_join(%lu) failed with error %s\n", handle[currentThreadCount], strerror(errno));
- refresh();
- }
- }
- }
- char textStrings[MAX_THREAD_NUMBER][50] =
- {
- "0-Nirvana ",
- "1-Queen ",
- "2-Scorpions ",
- "3-Metallica ",
- "4-Bon Jovi ",
- "5-The Final Countdown ",
- "6-Rammstein ",
- "7-Louna ",
- "8-Sonic Syndicate ",
- "9-Skillet "
- };
- void* writer(void* param)
- {
- int a = (int)param;
- while(quitThread[a] != 1)
- {
- if (pthread_mutex_trylock(&mu) == 0)
- {
- for (int i = 0; textStrings[a][i]; i++)
- {
- printw("%c", textStrings[a][i]);
- refresh();
- usleep(100000);
- }
- printw(" ");
- refresh();
- pthread_mutex_unlock(&mu);
- }
- }
- quitThread[a] = 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement