
Добавил:
chachshin_denis
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:1-2 курс (сорян, лень разбирать) / LR_2_1
.cpp#include "iostream"
#include "pthread.h"
#include "semaphore.h"
#include "unistd.h"
#include "string"
using namespace std;
sem_t semaphore;
int flag1 = 0;
int flag2 = 0;
string stroka = "";
void* potok1(void* flag)
{
int *n = (int *)flag;
while(*n == 0)
{
sem_wait(&semaphore);
for(int i = 0; i < 3; i++)
{
stroka += '1';
sleep(1);
}
sem_post(&semaphore);
sleep(1);
}
cout << "Поток №1 закончил работу\n";
pthread_exit(n);
}
void* potok2(void* flag)
{
int *n = (int *)flag;
while(*n == 0)
{
sem_wait(&semaphore);
for(int i = 0; i < 3; i++)
{
stroka += '2';
sleep(1);
}
sem_post(&semaphore);
sleep(1);
}
cout << "Поток №2 закончил работу\n";
pthread_exit(n);
}
int main()
{
cout << "Программа начала работу\n";
pthread_t id1, id2;
sem_init(&semaphore, 0, 1);
if (pthread_create(&id1, NULL, potok1, &flag1) == 0)
{
cout << "Поток №1 начал работу\n";
}
else
{
perror("pthread_create");
}
if (pthread_create(&id2, NULL, potok2, &flag2) == 0)
{
cout << "Поток №2 начал работу\n";
}
else
{
perror("pthread_create");
}
cout << "Нажмите Enter";
getchar();
cout << "Клавиша нажата\n";
*(&flag1) = *(&flag2) = 1;
void *res1, *res2;
pthread_join(id1, &res1);
pthread_join(id2, &res2);
cout << "Вывод с двух потоков: " << stroka << endl;
sem_destroy(&semaphore);
cout << "Программа завершила работу\n";
return 0;
}
Соседние файлы в папке 1-2 курс (сорян, лень разбирать)