Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <termios.h>
- #include <stdlib.h>
- static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- void* thread_routine(void* args)
- {
- while (1)
- {
- pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
- pthread_mutex_lock(&mutex);
- fprintf(stdout, "%s\n", (char*)args);
- pthread_mutex_unlock(&mutex);
- pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
- usleep(100);
- }
- pthread_exit(NULL);
- }
- struct stack
- {
- pthread_t thread;
- char* thread_output_string;
- struct stack* next;
- };
- void push(struct stack** head, pthread_t thread, char* thread_output_string)
- {
- struct stack* s = malloc(sizeof(struct stack));
- s->next = *head;
- s->thread_output_string = thread_output_string;
- s->thread = thread;
- *head = s;
- }
- int empty(struct stack* head)
- {
- return head == NULL;
- }
- pthread_t pop(struct stack** head)
- {
- if (empty(*head))
- {
- return -1;
- }
- struct stack* temp = *head;
- *head = temp->next;
- pthread_t thread = temp->thread;
- free(temp->thread_output_string);
- free(temp);
- return thread;
- }
- char* get_thread_string(int threads_count)
- {
- int lenght = snprintf(NULL, 0, "%d", threads_count);
- char* output_string = malloc(sizeof(char) * (lenght + 1));
- sprintf(output_string, "%d", threads_count);
- output_string[lenght] = '\0';
- return output_string;
- }
- void create_thread(struct stack** head, int threads_count)
- {
- pthread_t thread;
- char* thread_output_string = get_thread_string(threads_count);
- pthread_create(&thread, NULL, thread_routine, (void*)thread_output_string);
- push(head, thread, thread_output_string);
- }
- int terminate_thread(struct stack** head)
- {
- pthread_t thread;
- if ((thread = pop(head)) == -1)
- {
- return 0;
- }
- pthread_cancel(thread);
- return 1;
- }
- /* reads from keypress, doesn't echo */
- int getch(void)
- {
- struct termios oldattr, newattr;
- int ch;
- tcgetattr( STDIN_FILENO, &oldattr );
- newattr = oldattr;
- newattr.c_lflag &= ~( ICANON | ECHO );
- tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
- ch = getchar();
- tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
- return ch;
- }
- int main()
- {
- struct stack* head = NULL;
- int threads_count = 0;
- char c;
- while ((c = getch()) != 'q')
- {
- switch (c)
- {
- case '+':
- create_thread(&head, ++threads_count);
- break;
- case '-':
- terminate_thread(&head);
- break;
- default:
- break;
- }
- }
- while (terminate_thread(&head))
- ;
- pthread_mutex_destroy(&mutex);
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement