Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string>
- #include <string.h>
- #include <unistd.h>
- #include <pthread.h>
- #define STRING_LIMIT 100
- static pthread_mutex_t mute_lock;
- static pthread_cond_t conditional;
- struct str_array_t{
- bool quit;
- size_t num_strings;
- char** data;
- };
- void add_to_array(str_array_t* array, const char* str)
- {
- if(array->num_strings >= STRING_LIMIT)
- {
- free(array->data[array->num_strings % STRING_LIMIT]);
- array->data[array->num_strings++ % STRING_LIMIT] = strdup(str);
- }
- else
- {
- array->data[array->num_strings++] = strdup(str);
- }
- return;
- }
- const char* get_random_word()
- {
- static const char* words[9] = {"hello", "world", "fancy", "cruel", "school", "tool", "string", "bling"};
- return words[rand()%8];
- }
- void* producer(void* a)
- {
- str_array_t *array = (str_array_t*)a;
- char string[100];
- while(array->quit != true)
- {
- sleep(rand()%3);
- pthread_mutex_lock(&mute_lock);
- add_to_array(array, get_random_word());
- pthread_mutex_unlock(&mute_lock);
- pthread_cond_signal(&conditional);
- }
- free(array);
- exit(EXIT_SUCCESS);
- //return;
- }
- void* consumer(void* a)
- {
- str_array_t *array = (str_array_t*)a;
- pthread_mutex_lock(&mute_lock);
- size_t index = 0;
- size_t size = array->num_strings;
- while(size == 0)
- {
- pthread_cond_wait(&conditional, &mute_lock);
- size = array->num_strings;
- if(array->quit){ exit(EXIT_SUCCESS); }
- }
- while(array->quit != true){
- while(index < array->num_strings)
- {
- printf("got %s\n", array->data[index < STRING_LIMIT ? index++ : index++ % STRING_LIMIT]);
- sleep(rand() % 3);
- }
- pthread_mutex_unlock(&mute_lock);
- sleep(10);
- pthread_mutex_lock(&mute_lock);
- }
- free(array);
- exit(EXIT_SUCCESS);
- }
- int main(int argc, char* argv[])
- {
- pthread_t producer_thread, consumer_thread;
- str_array_t* array = new str_array_t;
- array->quit = false;
- array->num_strings = 0;
- array->data = new char*;
- int producer_flag, consumer_flag;
- producer_flag = pthread_create( &producer_thread, NULL, producer, (void*)array);
- if(producer_flag)
- {
- printf("errno %d\n", producer_flag);
- return EXIT_FAILURE;
- }
- consumer_flag = pthread_create( &consumer_thread, NULL, consumer, (void*)array);
- if(producer_flag)
- {
- printf("errno %d\n", consumer_flag);
- return EXIT_FAILURE;
- }
- char asd_msg[250] = "";
- bool asd_queued = false;
- const char* c_string;
- while(1){
- scanf("%s", asd_msg);
- if(strcmp(asd_msg, "quit") == 0){
- array->quit = true;
- exit(EXIT_SUCCESS);
- }
- asd_queued = true;
- while(asd_queued){
- pthread_mutex_lock(&mute_lock);
- add_to_array(array, asd_msg);
- pthread_mutex_unlock(&mute_lock);
- asd_queued = false;
- }
- sleep(1);
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement