Namespaces
Variants

std::shared_lock<Mutex>:: lock

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
void lock ( ) ;
(depuis C++14)

Verrouille le mutex associé en mode partagé. Appelle effectivement mutex ( ) - > lock_shared ( ) .

Table des matières

Paramètres

(aucun)

Valeur de retour

(aucun)

Exceptions

  • Toute exception levée par mutex ( ) - > lock_shared ( ) .

Exemple

#include <iostream>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
std::string file = "Original content."; // Simule un fichier
std::mutex output_mutex; // mutex qui protège les opérations de sortie.
std::shared_mutex file_mutex; // mutex lecteur/rédacteur
void read_content(int id)
{
    std::string content;
    {
        std::shared_lock lock(file_mutex, std::defer_lock); // Ne pas le verrouiller d'abord.
        lock.lock(); // Verrouiller ici.
        content = file;
    }
    std::lock_guard lock(output_mutex);
    std::cout << "Contents read by reader #" << id << ": " << content << '\n';
}
void write_content()
{
    {
        std::lock_guard file_lock(file_mutex);
        file = "New content";
    }
    std::lock_guard output_lock(output_mutex);
    std::cout << "New content saved.\n";
}
int main()
{
    std::cout << "Two readers reading from file.\n"
              << "A writer competes with them.\n";
    std::thread reader1{read_content, 1};
    std::thread reader2{read_content, 2};
    std::thread writer{write_content};
    reader1.join();
    reader2.join();
    writer.join();
    std::cout << "The first few operations to file are done.\n";
    reader1 = std::thread{read_content, 3};
    reader1.join();
}

Sortie possible :

Two readers reading from file.
A writer competes with them.
Contents read by reader #1: Original content.
Contents read by reader #2: Original content.
New content saved.
The first few operations to file are done.
Contents read by reader #3: New content

Voir aussi

tente de verrouiller le mutex associé
(fonction membre publique)
déverrouille le mutex associé
(fonction membre publique)