Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Parallel.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- /*
- pthread\include - здесь хедеры
- pthread\lib\x86 - используем pthreadVSE2.lib
- pthread\dll\x86 - используем pthreadVSE2.dll (нужно скопировать руками в
- папку с приложением, либо добавить post build event, который, бы это делал)
- */
- #include <pthread.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <iostream>
- #include <vector>
- #include <string>
- std::vector<std::string> books;
- pthread_mutex_t guardMutex;
- pthread_cond_t cond_reader,cond_writer;
- int numb_reader, numb_writer;
- void *reader(void* prm)
- {
- while(true)
- {
- pthread_mutex_lock(&guardMutex);
- bool is_full = books.size() > 50;
- if (books.empty())
- {
- pthread_cond_wait(&cond_reader, &guardMutex);
- }
- for (auto it = books.begin(); it != books.end(); ++it)
- {
- std::string rd = *it;
- std::cout << rd << std::endl;
- //std::cout << "OP - faggot " << std::endl;
- }
- if (is_full)
- {
- pthread_cond_signal(&cond_writer);
- }
- pthread_mutex_unlock(&guardMutex);
- }
- return 0;
- }
- void *writer(void *prm)
- {
- while (true){
- pthread_mutex_lock(&guardMutex);
- bool is_empty = books.empty();
- if (books.size() > 5)
- {
- pthread_cond_wait(&cond_writer, &guardMutex);
- }
- for (int i = 0; i < 100; i++)
- {
- int numb = rand();
- char *string = new char[10];
- itoa(numb, string, 10);
- std::string str = string;
- books.push_back(str);
- }
- if (is_empty)
- {
- pthread_cond_signal(&cond_reader);
- }
- pthread_mutex_unlock(&guardMutex);
- }
- return 0;
- }
- int main()
- {
- std::cout << "Write, how many reader and writer, next - push enter" << std::endl;
- std::cin >> numb_reader >> numb_writer;
- pthread_t thread_reader;
- pthread_t thread_writer;
- pthread_mutex_init(&guardMutex, 0);
- pthread_cond_init(&cond_reader, 0);
- pthread_cond_init(&cond_writer, 0);
- for (int i = 0; i < numb_reader; i++)
- {
- pthread_create(&thread_reader, 0, writer, 0);
- }
- for (int i = 0; i < numb_writer; i++)
- {
- pthread_create(&thread_writer, 0, reader, 0);
- }
- for (int i = 0; i < numb_reader; i++)
- {
- pthread_join(thread_reader, 0);
- }
- for (int i = 0; i < numb_writer; i++)
- {
- pthread_join(thread_writer, 0);
- }
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement