std::memory_order
Da cppreference.com
![]() |
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Definido no cabeçalho <atomic>
|
||
enum memory_order { memory_order_relaxed, |
(desde C++11) | |
std::memory_order
especifica como acessos não-atômicas de memória estão a ser ordenada em torno de uma operação atômica. A lógica disso é que, quando vários segmentos simultaneamente, ler e escrever a diversas variáveis em sistemas multi-core, um segmento pode ver a mudança de valores, de modo diferente do que outro segmento tem escrito. Além disso, o fim aparente de mudanças podem ser diferentes segmentos leitor diversas. A garantia de que toda a memória acessa a variáveis atômicas são seqüencial pode prejudicar o desempenho em alguns casos. std::memory_order
permite especificar as restrições de exatas que o compilador deve valer.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.
You can help to correct and verify the translation. Click here for instructions.
É possível especificar a ordem de memória personalizado para cada operação atômica na biblioteca através de um parâmetro adicional. O padrão é 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.
You can help to correct and verify the translation. Click here for instructions.
Índice |
[editar] Constantes
Defined in header
<atomic> | |
Valor
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
|
Relaxada 'pedido: não há restrições sobre o reordenamento dos acessos de memória em todo o variável atômica .
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
|
'Consumir' operação: não lê na atual segmento dependente do valor carregado atualmente podem ser reordenadas antes desta carga. Isso garante que escreve para variáveis dependentes em outros segmentos que liberam a mesma variável atômica são visíveis no segmento atual. Na maioria das plataformas, isso afeta a otimização do compilador só .
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
|
'Adquirir' operação: não lê no segmento atual podem ser reordenadas antes desta carga. Isso garante que todas as gravações em outros segmentos que liberam a mesma variável atômica são visíveis no segmento atual .
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
|
Operação Release': não escreve na linha atual pode ser reordenadas depois desta loja. Isso garante que todas as gravações na atual segmento são visíveis em outros segmentos que adquirem a mesma variável atômica .
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
|
Operação 'Adquirir liberação ": não lê no segmento atual podem ser reordenadas antes desta carga, bem como não escreve na linha atual pode ser reordenadas depois desta loja. A operação é ler-modificar-escrever a operação. É assegurado que todas as gravações em outros tópicos que liberam a mesma variável atômica são visíveis antes da modificação ea modificação é visível em outros segmentos que adquirem a mesma variável atômica .
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
|
Ordenação seqüencial. A operação tem a mesma semântica de adquirir liberação de operação e, adicionalmente, tem a operação em seqüência consistente ordenação .
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. |
[editar] Relaxado ordenação
Operações atómicas etiquetados std::memory_order_relaxed exibem as seguintes propriedades:
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.
You can help to correct and verify the translation. Click here for instructions.
- Sem ordenação dos acessos à memória outros é assegurada qualquer. Isto significa que não é possível sincronizar vários segmentos usando a variável atómica.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. - Lê e escreve para a variável atômica em si são ordenados. Uma vez que uma thread lê um valor, uma leitura posterior do mesmo segmento do mesmo objeto não pode produzir um valor anteriormente.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.
Por exemplo, com
x
e y
inicialmente 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.
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);
está autorizada a produzir
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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Lançamento-Consuma encomenda
Se um armazenamento atómica é marcado std::memory_order_release e uma carga atómica da mesma variável é marcado std::memory_order_consume, as operações de apresentar as seguintes propriedades:
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.
You can help to correct and verify the translation. Click here for instructions.
- Não escreve no segmento de escritor pode ser reordenadas após a loja atômicaOriginal:No writes in the writer thread can be reordered after the atomic storeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Não lê ou escreve dependente do valor recebido de carga atômica podem ser reordenadas antes da carga atômica. "Dependente" significa que o endereço ou o valor é calculado a partir do valor da variável atómica. Esta forma de sincronização entre threads é conhecido como "ordenação dependência".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. - A sincronização é estabelecida apenas entre os tópicos liberar e' consumindo a mesma variável atômica. Outros segmentos podem ver ordem diferente de acessos de memória do que um ou ambos os fios sincronizados.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. - A sincronização é transitivo. Isto é, se temos a seguinte situação: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.
- Tópico A libera variável atômica 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. - Tópico B consome variável atômica 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. - Variável atômica b depende a.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. - Tópico B variável lançamentos atômica 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. - Tópico C consome ou adquire variável atômica 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.
-
- Então, não só A e B ou B e C são sincronizados, mas A e C também. Isto é, todas as escritas pelo segmento A, que foram lançados antes do lançamento de a são garantidos para ser concluída uma vez rosca C observa a loja para 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.
Em todas as CPUs mainstream, que não DEC Alpha, ordenação de dependência é automático, não há instruções da CPU adicionais são emitidos para este modo de sincronização, apenas algumas otimizações do compilador são afetados (por exemplo, o compilador está proibida de realizar cargas especulativas sobre os objetos que estão envolvidos no dependência cadeia)
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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Solte seqüência
Se alguns atômica é a loja-lançado e vários outros segmentos realizar ler-modificar-escrever operações em que atômica, uma "sequência de lançamento" é formado: os tópicos que realizam a leitura-modificação-escreve para o atômica mesmo sincronizar com o primeiro segmento e outro, mesmo se eles não têm semântica
memory_order_release
. Isso faz único produtor - múltiplas situações possíveis consumidores sem impor sincronização desnecessária entre os segmentos individuais de consumo.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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Solte-Adquirir encomenda
Se um armazenamento atómica é marcado std::memory_order_release e uma carga atómica da mesma variável é marcado std::memory_order_acquire, as operações de apresentar as seguintes propriedades:
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.
You can help to correct and verify the translation. Click here for instructions.
- Não escreve no segmento de escritor pode ser reordenadas após a loja atômicaOriginal:No writes in the writer thread can be reordered after the atomic storeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Não lê no segmento leitor podem ser reordenadas antes da carga atômica.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. - A sincronização é estabelecida apenas entre os tópicos liberar e' adquirir a mesma variável atômica. Outros segmentos podem ver ordem diferente de acessos de memória do que um ou ambos os fios sincronizados.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. - A sincronização é transitivo. Isto é, se temos a seguinte situação: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.
- Tópico A libera variável atômica 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. - Tópico B consome variável atômica 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. - Tópico B variável lançamentos atômica 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. - Tópico C consome ou adquire variável atômica 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.
-
- Então, não só A e B ou B e C são sincronizados, mas A e C também. Isto é, todas as escritas pelo segmento A, que foram lançados antes do lançamento de a são garantidos para ser concluída uma vez rosca C observa a loja para 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.
Em sistemas fortemente ordenados (x86, SPARC, mainframe IBM), de liberação adquirir ordenação é automática. Não instruções adicionais de CPU são emitidos para este modo de sincronização, apenas otimizações do compilador certos são afetados (por exemplo, o compilador está proibido de se mover não atômica lojas após o atômica loja relase ou realizar não atômica cargas mais cedo do que a carga atômica adquirir)
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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Sequencialmente consistente ordenação
Se um armazenamento atómico e um é marcado std::memory_order_seq_cst e uma carga atómica da mesma variável é marcado std::memory_order_seq_cst, em seguida, as operações de apresentar as seguintes propriedades:
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.
You can help to correct and verify the translation. Click here for instructions.
- Não escreve no segmento de escritor pode ser reordenadas após a loja atômicaOriginal:No writes in the writer thread can be reordered after the atomic storeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Não lê no segmento leitor podem ser reordenadas antes da carga atômica.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. - A sincronização é estabelecida entre todas as operações atômicas marcadas std::memory_order_seq_cst. Todos os segmentos usando operação atômica como ver a mesma ordem de acessos à memória.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.
Ordenação seqüencial é necessário para muitas várias situações-produtor múltiplas de consumo, onde todos os consumidores devem observar as ações de todos os produtores que ocorrem na mesma ordem.
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.
You can help to correct and verify the translation. Click here for instructions.
Ordenação seqüencial total requer uma completa memória de instruções da CPU cerca em todos os sistemas multi-core. Isso pode se tornar um gargalo de desempenho, uma vez que obriga todos os acessos à memória para propagar para cada fio.
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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Relacionamento com volátil
{{{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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Exemplos
[editar] std::memory_order_relaxed
O exemplo a seguir demonstra uma tarefa (atualização de um contador global) que requer atomicidade, mas não há restrições de ordenação desde não atômica memória não está envolvido .
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.
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'; }
Saída:
Final counter value is 10000
[editar] std::memory_order_release
and std::memory_order_consume
Este exemplo demonstra a dependência ordenada sincronização: o de dados inteiro não está relacionado com o ponteiro de cadeia por uma relação de dados-dependência, assim o seu valor é indefinido no consumidor .
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.
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(); }
[editar] std::memory_order_release
and memory_order_acquire
Mutexes, filas de concorrentes e outros produtores-consumidores situações exigem libertação ordenação no segmento de editora e adquirir ordenação no segmento de consumidor. Este padrão estabelece a sincronização entre threads pares .
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.
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(); }
[editar] std::memory_order_acq_rel
O exemplo seguinte demonstra transitivo liberar-ordenação adquirir em três tópicos
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.
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(); }
[editar] std::memory_order_seq_cst
Este exemplo demonstra uma situação em que a ordem sequencial é necessário. Qualquer outra classificação pode desencadear a afirmar porque seria possível que os fios e
c
d
observar alterações nas atómica x
e y
em ordem oposta .
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.
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 }