/
AirLexa
/
06
Обзор
Документация
Войти
/
AirLexa
/
06
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lesson_02/Task_2/Task_2.cpp
79 строк
2 KB
AirLexa
урок 2
17 июн 2026, 14:06
Верифицирован
17 июн 2026, 14:06
4dab469
Код
Авторство
О чём код?
#include <thread> #include <string> #include <vector> #include <sstream> #include <mutex> #include <windows.h> #include <iostream> std::mutex m; std::string get_work() { if (rand() % 11 == 3) // 1 раз из 10-ти делаем ошибку throw std::runtime_error("Ошибка!!"); return "0"; } void print(std::vector<std::string>& res) { // выводим на печать строки вектора system("cls"); for (std::string s : res) std::cout << s << std::endl; } void task(std::vector<std::string>& res, int num_thread, int dt) { // функция работы потока for (int i = 0; i < 10; i++) { m.lock(); if (i == 0) { // первый раз, записываем исходные данные std::stringstream ss; ss << std::this_thread::get_id(); res[num_thread].append(std::to_string(num_thread + 1)) .append(": ").append(ss.str()).append(" "); } try { // 1 раз из 10-ти может выскочить ошибка std::string s = get_work(); res[num_thread].append(s); } catch (const std::runtime_error& e) { res[num_thread].append("X"); } if (i == 9) res[num_thread].append(" ") // крайний символ записываем время работы .append(std::to_string(dt / 100)) .append("сек."); print(res); m.unlock(); Sleep(dt); } } int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); srand(time(0)); int thread_count = 0; std::cout << "Введите количество потоков: "; std::cin >> thread_count; std::vector<std::thread> threads(thread_count); std::vector<std::string> res(thread_count); std::vector<int> thread_time(thread_count); int tmp = 0; for (int i = 0; i < thread_count; i++) { std::cout << "Введите время потока " << (i + 1) << " (сек): "; std::cin >> tmp; thread_time[i] = tmp; } for (int i = 0; i < thread_count; i++) threads[i] = std::thread(task, std::ref(res), i, thread_time[i] * 100); for (auto& thread : threads) thread.join(); return 0; }