Concurrency: Più Mani sul Banco

🏎️ Concurrency: Più Mani sul Banco

Per ottimizzare i calcoli complessi (AI o rendering 3D), sfruttiamo il multi-threading. Con il C++20, la gestione dei thread è diventata molto più robusta.

1. std::jthread: Il Thread Cooperativo

A differenza del vecchio std::thread, std::jthread (Joining Thread) gestisce automaticamente la chiusura (join) e supporta la richiesta di interruzione.

#include <thread>
#include <stop_token>
#include <iostream>

void background_worker(std::stop_token stoken) {
    while (!stoken.stop_requested()) {
        // Esegue calcoli in background
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    std::cout << "Worker stopped safely.\n";
}

int main() {
    std::jthread worker(background_worker);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    // worker si chiude automaticamente qui
    return 0;
}

2. Sincronizzazione

  • std::mutex & std::lock_guard: Per proteggere i dati condivisi.
  • std::atomic: Per variabili semplici che devono essere thread-safe senza lock pesanti.
Last updated on Sunday, February 15, 2026
Built with Hugo
Theme Stack designed by Jimmy