Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Written 16. November 2014 by Kai Nilsen
- */
- #include <stdio.h>
- #include <pthread.h>
- #include <string>
- #include <iostream>
- #include <sstream>
- using namespace std;
- int const NUM_THREADS = 3;
- pthread_t threads[NUM_THREADS];
- int global = 0;
- int globalOut = 0;
- bool quit = false;
- pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t ready = PTHREAD_COND_INITIALIZER, work = PTHREAD_COND_INITIALIZER, print = PTHREAD_COND_INITIALIZER;
- int input();
- void* inFunc(void* param)
- {
- int number;
- int loop = 0;
- while (quit != true)
- {
- pthread_mutex_lock(&lock);
- if (global == 0 && globalOut == 0)
- {
- number = input();
- if (number != 0)
- {
- printf(" inFunc sending %d\n", number);
- global = number;
- }
- else
- {
- global = number;
- quit = true;
- }
- }
- pthread_cond_signal(&work);
- pthread_mutex_unlock(&lock);
- loop++;
- pthread_cond_wait(&ready, &lock);
- }
- printf("inFunc looped %d\n", loop);
- pthread_exit(0);
- return 0;
- }
- void* workFunc(void* param)
- {
- int loop = 0;
- while (quit != true)
- {
- pthread_mutex_lock(&lock);
- pthread_cond_wait(&work, &lock);
- if (global != 0 && globalOut == 0)
- {
- if (global != 0)
- {
- globalOut = global * 3;
- printf(" workFunc turning %d into %d\n", global, globalOut);
- global = 0;
- }
- }
- pthread_mutex_unlock(&lock);
- pthread_cond_signal(&print);
- loop++;
- }
- printf("workFunc looped %d\n", loop);
- pthread_exit(0);
- return 0;
- }
- void* outFunc(void* param)
- {
- int loop = 0;
- while (quit != true)
- {
- pthread_mutex_lock(&lock);
- pthread_cond_wait(&print, &lock);
- if (globalOut != 0 && global == 0)
- {
- if (globalOut != 0)
- {
- printf(" outFunc printing %d\n", globalOut);
- globalOut = 0;
- }
- }
- pthread_mutex_unlock(&lock);
- pthread_cond_signal(&ready);
- loop++;
- }
- printf("outFunc looped %d\n", loop);
- pthread_exit(0);
- return 0;
- }
- int main()
- {
- pthread_create(&threads[0], NULL, inFunc, NULL);
- pthread_create(&threads[1], NULL, workFunc, NULL);
- pthread_create(&threads[2], NULL, outFunc, NULL);
- for (int i = 0; i < NUM_THREADS; i++)
- {
- pthread_join(threads[i], NULL);
- }
- pthread_mutex_destroy(&lock);
- system("pause");
- return 0;
- }
- int input()
- {
- char input[10];
- int number;
- bool validNumber = false;
- while (validNumber != true)
- {
- printf("> ");
- gets_s(input);
- for (int i = 0; i < strlen(input); i++)
- {
- if (i == 0 && input[0] == '-' && (input[1] <= '9' && input[1] >= '0'))
- {
- validNumber = true;
- }
- else if (input[i] <= '9' && input[i] >= '0')
- {
- validNumber = true;
- }
- else
- {
- validNumber = false;
- break;
- }
- }
- if (validNumber == false && input[0] == 'q' && strlen(input) == 1)
- {
- number = 0;
- validNumber = true;
- }
- else if (validNumber == true)
- {
- number = stoi(input);
- }
- }
- return number;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement