Namespace
Varianti

std::memory_order

Da cppreference.com.
< cpp‎ | atomic

 
 
Atomic operazioni di biblioteca
Tipi
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
atomic(C++11)
atomic_is_lock_free(C++11)
Funzioni
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
atomic_store
atomic_store_explicit
(C++11)
(C++11)
atomic_load
atomic_load_explicit
(C++11)
(C++11)
atomic_exchange
atomic_exchange_explicit
(C++11)
(C++11)
atomic_compare_exchange_weak
atomic_compare_exchange_weak_explicit
atomic_compare_exchange_strong
atomic_compare_exchange_strong_explicit
(C++11)
(C++11)
(C++11)
(C++11)
atomic_fetch_add
atomic_fetch_add_explicit
(C++11)
(C++11)
atomic_fetch_sub
atomic_fetch_sub_explicit
(C++11)
(C++11)
atomic_fetch_and
atomic_fetch_and_explicit
(C++11)
(C++11)
atomic_fetch_or
atomic_fetch_or_explicit
(C++11)
(C++11)
atomic_fetch_xor
atomic_fetch_xor_explicit
(C++11)
(C++11)
Bandiere Atomic
Original:
Atomic flags
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
atomic_flag(C++11)
atomic_flag_test_and_set
atomic_flag_test_and_set_explicit
(C++11)
(C++11)
atomic_flag_clear
atomic_flag_clear_explicit
(C++11)
(C++11)
Inizializzazione
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
atomic_init(C++11)
ATOMIC_VAR_INIT(C++11)
ATOMIC_FLAG_INIT(C++11)
Memoria di ordinazione
Original:
Memory ordering
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
memory_order(C++11)
kill_dependency(C++11)
atomic_thread_fence(C++11)
atomic_signal_fence(C++11)
 
Defined in header <atomic>
enum memory_order {

    memory_order_relaxed,
    memory_order_consume,
    memory_order_acquire,
    memory_order_release,
    memory_order_acq_rel,
    memory_order_seq_cst

};
(dal C++11)
std::memory_order specifica come non-atomiche accessi alla memoria devono essere ordinati intorno a un operazione atomica. La ragione di questo è che quando più thread contemporaneamente in lettura e scrittura a più variabili su sistemi multi-core, un thread potrebbe vedere i valori cambiano in modo diverso da un altro thread li ha scritti. Inoltre, l'ordine apparente di modifiche possono essere diversi tra thread di lettura diverse. Assicurare che tutti gli accessi alla memoria di variabili atomiche sono sequenziale può influire negativamente sulle prestazioni in alcuni casi. std::memory_order consente di specificare i vincoli esatti che il compilatore deve far rispettare.
Original:
std::memory_order specifies how non-atomic memory accesses are to be ordered around an atomic operation. The rationale of this is that when several threads simultaneously read and write to several variables on multi-core systems, one thread might see the values change in different order than another thread has written them. Also, the apparent order of changes may be different across several reader threads. Ensuring that all memory accesses to atomic variables are sequential may hurt performance in some cases. std::memory_order allows to specify the exact constraints that the compiler must enforce.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
E 'possibile specificare l'ordine personalizzato memoria per ogni operazione atomica nella libreria tramite un parametro aggiuntivo. Il valore predefinito è std::memory_order_seq_cst.
Original:
It's possible to specify custom memory order for each atomic operation in the library via an additional parameter. The default is std::memory_order_seq_cst.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Indice

[modifica] Costanti

Defined in header <atomic>
Valore
Original:
Value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Explanation
memory_order_relaxed
Relaxed' ordine: non ci sono vincoli sul riordino degli accessi di memoria in tutto il variabile atomica .
Original:
Relaxed' ordering: there are no constraints on reordering of memory accesses around the atomic variable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
memory_order_consume
'Consumare' lavoro: nessuna legge nel thread corrente dipende dal valore attualmente caricato possono essere riordinate prima di questo carico. Questo assicura che scrive variabili dipendenti di altri thread che rilasciano la stessa variabile atomica sono visibili nel thread corrente. Sulla maggior parte delle piattaforme, questo riguarda l'ottimizzazione del compilatore solo .
Original:
Consume operation: no reads in the current thread dependent on the value currently loaded can be reordered before this load. This ensures that writes to dependent variables in other threads that release the same atomic variable are visible in the current thread. On most platforms, this affects compiler optimization only.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
memory_order_acquire
'Acquire' lavoro: nessuna legge nel thread corrente possono essere riordinate prima di questo carico. Questo assicura che tutte le scritture in altri thread che rilasciano la stessa variabile atomica sono visibili nel thread corrente .
Original:
Acquire operation: no reads in the current thread can be reordered before this load. This ensures that all writes in other threads that release the same atomic variable are visible in the current thread.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
memory_order_release
Operazione uscita': non scrive nel thread corrente possono essere riordinate dopo questo negozio. Questo assicura che tutte le scritture nel thread corrente sono visibili in altri thread che acquisiscono la stessa variabile atomica .
Original:
Release' operation: no writes in the current thread can be reordered after this store. This ensures that all writes in the current thread are visible in other threads that acquire the same atomic variable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
memory_order_acq_rel
Operazione 'Acquire-release': non legge il thread corrente possono essere riordinate prima di questo carico così come non scrive nel thread corrente possono essere riordinate dopo questo negozio. L'operazione è lettura-modifica-scrittura. Viene assicurato che tutte le scritture in un altro thread che rilasciano la stessa variabile atomica sono visibili prima della modifica e la modifica è visibile in altri thread che acquisiscono la stessa variabile atomica .
Original:
Acquire-release operation: no reads in the current thread can be reordered before this load as well as no writes in the current thread can be reordered after this store. The operation is read-modify-write operation. It is ensured that all writes in another threads that release the same atomic variable are visible before the modification and the modification is visible in other threads that acquire the same atomic variable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
memory_order_seq_cst
'Ordinamento sequenziale'. L'operazione ha la stessa semantica di acquisire a rilascio funzionamento, e ha inoltre il funzionamento in sequenza coerente di ordinazione .
Original:
Sequential ordering. The operation has the same semantics as acquire-release operation, and additionally has sequentially-consistent operation ordering.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifica] Relaxed ordinamento

Operazioni atomiche targhetta std::memory_order_relaxed presentano le seguenti proprietà:
Original:
Atomic operations tagged std::memory_order_relaxed exhibit the following properties:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Nessun ordinamento accessi alla memoria altri è garantita alcuna. Ciò significa che non è possibile sincronizzare molti thread utilizzando la variabile atomica.
    Original:
    No ordering of other memory accesses is ensured whatsoever. This means that it is not possible to synchronize several threads using the atomic variable.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Legge e scrive alla variabile atomica sono ordinati in sé. Una volta che un thread legge un valore, una lettura successiva da un filo dallo stesso oggetto non può produrre un valore precedente.
    Original:
    Reads and writes to the atomic variable itself are ordered. Once a thread reads a value, a subsequent read by the same thread from the same object can not yield an earlier value.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Per esempio, con x e y inizialmente zero,
Original:
For example, with x and y initially zero,
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

// Thread 1:
r1 = y.load(memory_order_relaxed);
x.store(r1, memory_order_relaxed);
// Thread 2:
r2 = x.load(memory_order_relaxed);
y.store(42, memory_order_relaxed);

è permesso di produrre r1 == r2 == 42.
Original:
is allowed to produce r1 == r2 == 42.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifica] Release-Consumare ordinazione

Se un negozio atomico viene etichettato std::memory_order_release e un carico atomico dalla stessa variabile viene etichettato std::memory_order_consume, le operazioni presentano le seguenti proprietà:
Original:
If an atomic store is tagged std::memory_order_release and an atomic load from the same variable is tagged std::memory_order_consume, the operations exhibit the following properties:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Non scrive nel thread di scrittura possono essere riordinate dopo il negozio atomica
    Original:
    No writes in the writer thread can be reordered after the atomic store
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Nessuna legge o scrive dipende dal valore ricevuto dal carico atomico possono essere riordinate prima del carico atomico. "Dipendente" significa che l'indirizzo o valore è calcolato dal valore della variabile atomica. Questa forma di sincronizzazione tra thread è conosciuto come "ordinamento dipendenza".
    Original:
    No reads or writes dependent on the value received from atomic load can be reordered before the atomic load. "Dependent on" means that the address or value is computed from the value of the atomic variable. This form of synchronization between threads is known as "dependency ordering".
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • La sincronizzazione viene stabilita solo tra i fili liberare' e consumando la stessa variabile atomica. Altri thread possono vedere diverso ordine di accessi alla memoria di uno o entrambi i fili sincronizzate.
    Original:
    The synchronization is established only between the threads releasing and consuming the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • La sincronizzazione è transitiva. Cioè, se abbiamo la seguente situazione:
    Original:
    The synchronization is transitive. That is, if we have the following situation:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione A rilascia atomico variabile a.
    Original:
    Thread A releases atomic variable a.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione B consuma atomico variabile a.
    Original:
    Thread B consumes atomic variable a.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Variabile atomica b dipende da un'.
    Original:
    Atomic variable b is dependent on a.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione B variabile comunicati atomica b.
    Original:
    Thread B releases atomic variable b.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione C consuma o acquista atomico variabile b.
    Original:
    Thread C consumes or acquires atomic variable b.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Quindi non solo A e B o B e C sono sincronizzati, ma A e C anche. Cioè, tutte le scritture dal filo A che sono stati lanciati prima del rilascio di un' sono garantiti per essere completato una volta filo C osserva il negozio a b.
Original:
Then not only A and B or B and C are synchronized, but A and C also. That is, all writes by the thread A that were launched before the release of a are guaranteed to be completed once thread C observes the store to b.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Su tutte le CPU mainstream, oltre DEC Alpha, ordinamento dipendenza è automatico, senza istruzioni della CPU aggiuntive sono rilasciati per la modalità di sincronizzazione, solo alcune ottimizzazioni del compilatore sono interessati (ad esempio, il compilatore è un divieto di svolgere carichi speculative sugli oggetti che sono coinvolti nella dipendenza catena)
Original:
On all mainstream CPUs, other than DEC Alpha, dependency ordering is automatic, no additional CPU instructions are issued for this synchronization mode, only certain compiler optimizations are affected (e.g. the compiler is prohibited from performing speculative loads on the objects that are involved in the dependency chain)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifica] Rilasciare sequenza

Se qualche atomica è store-rilasciato e molti altri thread eseguire lettura-modifica-le operazioni di scrittura su quella atomica, una "sequenza di sblocco" è formato: tutti i thread che eseguono la lettura-modifica-scrittura nel atomico stesso la sincronizzazione con il primo thread e l'altro, anche se non hanno semantica memory_order_release. Questo rende unico produttore - più situazioni possibili consumatori senza imporre inutili sincronizzazione tra i thread individuali dei consumatori.
Original:
If some atomic is store-released and several other threads perform read-modify-write operations on that atomic, a "release sequence" is formed: all threads that perform the read-modify-writes to the same atomic synchronize with the first thread and each other even if they have no memory_order_release semantics. This makes single producer - multiple consumers situations possible without imposing unnecessary synchronization between individual consumer threads.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifica] Rilasciare-Acquisire ordinazione

Se un negozio atomico viene etichettato std::memory_order_release e un carico atomico dalla stessa variabile viene etichettato std::memory_order_acquire, le operazioni presentano le seguenti proprietà:
Original:
If an atomic store is tagged std::memory_order_release and an atomic load from the same variable is tagged std::memory_order_acquire, the operations exhibit the following properties:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Non scrive nel thread di scrittura possono essere riordinate dopo il negozio atomica
    Original:
    No writes in the writer thread can be reordered after the atomic store
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Nessuna legge nel thread di lettura possono essere riordinate prima del carico atomico.
    Original:
    No reads in the reader thread can be reordered before the atomic load.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • La sincronizzazione viene stabilita solo tra i fili rilascio e l'acquisizione la stessa variabile atomica. Altri thread possono vedere diverso ordine di accessi alla memoria di uno o entrambi i fili sincronizzate.
    Original:
    The synchronization is established only between the threads releasing and acquiring the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • La sincronizzazione è transitiva. Cioè, se abbiamo la seguente situazione:
    Original:
    The synchronization is transitive. That is, if we have the following situation:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione A rilascia atomico variabile a.
    Original:
    Thread A releases atomic variable a.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione B consuma atomico variabile a.
    Original:
    Thread B consumes atomic variable a.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione B variabile comunicati atomica b.
    Original:
    Thread B releases atomic variable b.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Discussione C consuma o acquista atomico variabile b.
    Original:
    Thread C consumes or acquires atomic variable b.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Quindi non solo A e B o B e C sono sincronizzati, ma A e C anche. Cioè, tutte le scritture dal filo A che sono stati lanciati prima del rilascio di un' sono garantiti per essere completato una volta filo C osserva il negozio a b.
Original:
Then not only A and B or B and C are synchronized, but A and C also. That is, all writes by the thread A that were launched before the release of a are guaranteed to be completed once thread C observes the store to b.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Sui sistemi fortemente ordinate (x86, SPARC, mainframe IBM), release-acquisire ordini è automatica. Non ci sono ulteriori istruzioni della CPU sono rilasciati per la modalità di sincronizzazione, solo alcune ottimizzazioni del compilatore sono interessati (ad esempio, il compilatore è fatto divieto di movimento non-atomiche negozi oltre l'atomica negozio-relase o eseguire non atomici carichi prima del carico atomico-acquisizione)
Original:
On strongly-ordered systems (x86, SPARC, IBM mainframe), release-acquire ordering is automatic. No additional CPU instructions are issued for this synchronization mode, only certain compiler optimizations are affected (e.g. the compiler is prohibited from moving non-atomic stores past the atomic store-relase or perform non-atomic loads earlier than the atomic load-acquire)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifica] Sequenza coerente con l'ordinazione

Se un negozio atomico e una è etichettato std::memory_order_seq_cst e un carico atomico dalla stessa variabile viene etichettato std::memory_order_seq_cst, allora le operazioni presentano le seguenti proprietà:
Original:
If an atomic store and an is tagged std::memory_order_seq_cst and an atomic load from the same variable is tagged std::memory_order_seq_cst, then the operations exhibit the following properties:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Non scrive nel thread di scrittura possono essere riordinate dopo il negozio atomica
    Original:
    No writes in the writer thread can be reordered after the atomic store
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Nessuna legge nel thread di lettura possono essere riordinate prima del carico atomico.
    Original:
    No reads in the reader thread can be reordered before the atomic load.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • La sincronizzazione si instaura tra tutte le operazioni atomiche tag std::memory_order_seq_cst. Tutti i thread che utilizzano tale operazione atomica vedere lo stesso ordine di accessi alla memoria.
    Original:
    The synchronization is established between all atomic operations tagged std::memory_order_seq_cst. All threads using such atomic operation see the same order of memory accesses.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Ordine sequenziale è necessario per molti più produttori-consumatori più situazioni in cui tutti i consumatori devono osservare le azioni di tutti i produttori che si verificano nello stesso ordine.
Original:
Sequential ordering is necessary for many multiple producer-multiple consumer situations where all consumers must observe the actions of all producers occurring in the same order.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Totale ordine sequenziale richiede una recinzione completa di istruzioni della CPU su tutti i sistemi multi-core. Questo può diventare un collo di bottiglia in quanto costringe tutta la memoria accessi di propagare a ogni thread.
Original:
Total sequential ordering requires a full memory fence CPU instruction on all multi-core systems. This may become a performance bottleneck since it forces all memory accesses to propagate to every thread.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifica] Rapporti con volatili

{{{1}}}
Original:
{{{2}}}
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifica] Esempi

[modifica] std::memory_order_relaxed

L'esempio seguente mostra un compito (l'aggiornamento di un contatore globale) che richiede atomicità, ma senza vincoli di ordinamento da non-atomica memoria non è coinvolto .
Original:
The following example demonstrates a task (updating a global counter) that requires atomicity, but no ordering constraints since non-atomic memory is not involved.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <vector>
#include <iostream>
#include <thread>
#include <atomic>
 
std::atomic<int> cnt = ATOMIC_VAR_INIT(0);
 
void f()
{
    for(int n = 0; n < 1000; ++n) {
        cnt.fetch_add(1, std::memory_order_relaxed);
    }
}
 
int main()
{
    std::vector<std::thread> v;
    for(int n = 0; n < 10; ++n) {
        v.emplace_back(f);
    }
    for(auto& t : v) {
        t.join();
    }
    std::cout << "Final counter value is " << cnt << '\n';
}

Output:

Final counter value is 10000

[modifica] std::memory_order_release and std::memory_order_consume

Questo esempio dimostra la dipendenza-ordinato la sincronizzazione: i dati integer non è correlato al puntatore alla stringa da un rapporto di dipendenza dei dati, quindi il suo valore non è definito nel consumatore .
Original:
This example demonstrates dependency-ordered synchronization: the integer data is not related to the pointer to string by a data-dependency relationship, thus its value is undefined in the consumer.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <thread>
#include <atomic>
#include <cassert>
#include <string>
 
std::atomic<std::string*> ptr;
int data;
 
void producer()
{
    std::string* p  = new std::string("Hello");
    data = 42;
    ptr.store(p, std::memory_order_release);
}
 
void consumer()
{
    std::string* p2;
    while (!(p2 = ptr.load(std::memory_order_consume)))
        ;
    assert(*p2 == "Hello"); // never fires
    assert(data == 42); // may or may not fire
}
 
int main()
{
    std::thread t1(producer);
    std::thread t2(consumer);
    t1.join(); t2.join();
}


[modifica] std::memory_order_release and memory_order_acquire

Mutex, code e altri concorrenti, tra produttori e consumatori situazioni di imporre la cessione di ordinazione nel thread editore e acquisire ordini nel thread consumatore. Questo modello stabilisce la sincronizzazione a due a due tra i thread .
Original:
Mutexes, concurrent queues, and other producer-consumer situations require release ordering in the publisher thread and acquire ordering in the consumer thread. This pattern establishes pairwise synchronization between threads.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <thread>
#include <atomic>
#include <cassert>
#include <string>
 
std::atomic<std::string*> ptr;
int data;
 
void producer()
{
    std::string* p  = new std::string("Hello");
    data = 42;
    ptr.store(p, std::memory_order_release);
}
 
void consumer()
{
    std::string* p2;
    while (!(p2 = ptr.load(std::memory_order_acquire)))
        ;
    assert(*p2 == "Hello"); // never fires
    assert(data == 42); // never fires
}
 
int main()
{
    std::thread t1(producer);
    std::thread t2(consumer);
    t1.join(); t2.join();
}


[modifica] std::memory_order_acq_rel

L'esempio seguente mostra transitiva rilasciare-acquisire ordini in tre fili
Original:
The follow example demonstrates transitive release-acquire ordering across three threads
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <thread>
#include <atomic>
#include <cassert>
#include <vector>
 
std::vector<int> data;
std::atomic<int> flag = ATOMIC_VAR_INIT(0);
 
void thread_1()
{
    data.push_back(42);
    flag.store(1, std::memory_order_release);
}
 
void thread_2()
{
    int expected=1;
    while (!flag.compare_exchange_strong(expected, 2, std::memory_order_acq_rel)) {
        expected = 1;
    }
}
 
void thread_3()
{
    while (flag.load(std::memory_order_acquire) < 2)
        ;
    assert(data.at(0) == 42); // will never fire
}
 
int main()
{
    std::thread a(thread_1);
    std::thread b(thread_2);
    std::thread c(thread_3);
    a.join(); b.join(); c.join();
}


[modifica] std::memory_order_seq_cst

Questo esempio mostra una situazione in cui è necessario ordinamento sequenziale. Qualsiasi altro ordinamento può far scattare l'asserzione in quanto sarebbe possibile per i fili e c d per osservare le modifiche alle atomiche x e y in ordine inverso .
Original:
This example demonstrates a situation where sequential ordering is necessary. Any other ordering may trigger the assert because it would be possible for the threads c and d to observe changes to the atomics x and y in opposite order.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <thread>
#include <atomic>
#include <cassert>
 
std::atomic<bool> x = ATOMIC_VAR_INIT(false);
std::atomic<bool> y = ATOMIC_VAR_INIT(false);
std::atomic<int> z = ATOMIC_VAR_INIT(0);
 
void write_x()
{
    x.store(true, std::memory_order_seq_cst);
}
 
void write_y()
{
    y.store(true, std::memory_order_seq_cst);
}
 
void read_x_then_y()
{
    while (!x.load(std::memory_order_seq_cst))
        ;
    if (y.load(std::memory_order_seq_cst)) {
        ++z;
    }
}
 
void read_y_then_x()
{
    while (!y.load(std::memory_order_seq_cst))
        ;
    if (x.load(std::memory_order_seq_cst)) {
        ++z;
    }
}
 
int main()
{
    std::thread a(write_x);
    std::thread b(write_y);
    std::thread c(read_x_then_y);
    std::thread d(read_y_then_x);
    a.join(); b.join(); c.join(); d.join();
    assert(z.load() != 0);  // will never happen
}