Untitled
#include <iostream> #include <vector> #include <thread> #include <future> #include <chrono> // Funkcja wykonywana przez każdy wątek void threadFunction(int id, std::promise<int> resultPromise) { std::this_thread::sleep_for(std::chrono::milliseconds(100 * id)); // Symulacja pracy int result = id * 10; // Przykładowy wynik obliczeń resultPromise.set_value(result); // Ustawienie wyniku } int main() { const int n = 5; // Liczba wątków // Wektory przechowujące obiekty promise, future oraz wątki std::vector<std::promise<int>> promises(n); std::vector<std::future<int>> futures; std::vector<std::thread> threads; // Tworzenie wątków for (int i = 0; i < n; ++i) { futures.push_back(promises[i].get_future()); // Pobranie future z promise threads.emplace_back(threadFunction, i, std::move(promises[i])); // Uruchomienie wątku } // Oczekiwanie na zakończenie wątków for (auto& t : threads) { if (t.joinable()) { t.join(); } } // Pobieranie wyników z wątków for (int i = 0; i < n; ++i) { int result = futures[i].get(); // Pobranie wyniku std::cout << "Result from thread " << i << ": " << result << '\n'; } return 0; }
Leave a Comment