/
rgd045
/
cpp-oop-basics
Обзор
Документация
Войти
/
rgd045
/
cpp-oop-basics
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
projects/lock/main.cpp
71 строка
2 KB
OMP Education
Add modules
28 июн 2024, 01:09
28 июн 2024, 01:09
0ef3df8
Код
Авторство
О чём код?
// SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru> // SPDX-License-Identifier: BSD-3-Clause #include <iostream> #include <thread> #include <chrono> #include <queue> #include <mutex> using namespace std::chrono_literals; std::mutex lock{}; void worker(std::queue<int>* queue) { int data {}; bool newData {false}; while(true) { newData = false; lock.lock(); if (!queue->empty()) { data = queue->front(); queue->pop(); newData = true; } lock.unlock(); if (newData) { if (data < 0) { std::cout << "Thread " << std::this_thread::get_id() << " stop!" << std::endl; break; } std::cout << "Thread " << std::this_thread::get_id() << " process " << data << std::endl; std::this_thread::sleep_for(500ms); } else { std::this_thread::sleep_for(5ms); } } } int main() { std::queue<int> queue; const int nworkers {4}; std::thread workers[nworkers] = {}; for (int i{0}; i<nworkers; i++) { workers[i] = std::thread {worker, &queue}; } std::this_thread::sleep_for(1s); for (int i{}; i < 10; i++) { lock.lock(); std::cout << "Push new task to queue: " << i << std::endl; queue.push(i); lock.unlock(); std::this_thread::sleep_for(200ms); } for (int i{0}; i<nworkers; i++) { queue.push(-1); } for (int i{0}; i<nworkers; i++) { workers[i].join(); } return 0; }