Скачиваний:
0
Добавлен:
18.10.2024
Размер:
2.29 Кб
Скачать
#include "iostream"
#include "pthread.h"
#include "semaphore.h"
#include "unistd.h"
#include "string"
#include "errno.h"

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)
    {
        int block_value = sem_trywait(&semaphore);
        if (block_value == -1){
            cout << "Ошибка доступа к критическому участку в потоке №1" << endl;
            sleep(1);
            continue;
        }
        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)
    {
        int block_value = sem_trywait(&semaphore);
        if (block_value == -1){
            cout << "Ошибка доступа к критическому участку в потоке №2" << endl;
            sleep(1);
            continue;
        }
        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\n";
    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 курс (сорян, лень разбирать)