Пространства имён
Варианты
Действия

memory_order

Материал из cppreference.com
< c | atomic

Заголовочный файл <stdatomic.h>
(начиная с C11)
memory_order определяет, как неатомической доступа к памяти должны быть заказаны по всему атомарные операции. Обоснованием этого является то, что, когда несколько потоков одновременно читать и писать на нескольких переменных на многоядерных системах, один поток может' увидеть изменение значений в ином порядке, чем другой поток их написал. Кроме того, очевидно порядок изменения могут быть различными по несколько потоков читателя. Обеспечение того, чтобы все доступ к памяти атомных переменных последовательное может повредить производительности в некоторых случаях. std::memory_order позволяет указать точные ограничения, которые компилятор должен исполнение.
Original:
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.
Это можно указать пользовательский порядок памяти для каждой атомарной операции в библиотеке с помощью дополнительного параметра. По умолчанию 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.

Содержание

[править] Константы

Определено в файле <atomic>
Value
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' заказ: нет ограничений на изменение порядка доступа к памяти вокруг атомного переменной .
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
'Потребление' работы: не читается в текущем потоке, зависит от значения в настоящее время загружены могут быть перераспределены до этой нагрузки. Это гарантирует, что пишет зависимые переменные в других потоках, которые выпускают те же атомные переменные видны в текущем потоке. На большинстве платформ, это сказывается на оптимизации компиляторов только .
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
'Приобретает' работы: не читается в текущий поток может быть заказана до этой нагрузки. Это гарантирует, что все записи в другие темы, которые выпускают те же атомные переменные видны в текущем потоке .
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
Операции 'Release': не пишет в текущий поток может быть заказана через этот магазин. Это гарантирует, что все записи в текущем потоке видны в других потоков, которые приобретают то же атомарных переменных .
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
'Приобретать-релиз' работы: не читается в текущий поток может быть заказана до этой нагрузки, а также не пишет в текущий поток может быть заказана через этот магазин. Операция чтения-модификации-записи. Он заверил, что все записи в другой темы, которые выпускают те же атомные переменные видны до изменения и модификации видно в других потоков, которые приобретают такой же атомарных переменных .
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
'Последовательного упорядочения'. Операция имеет ту же семантику, приобретают-релизе операции, и дополнительно имеет последовательно-последовательной операции заказа .
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.

[править] Непринужденная упорядочения

Атомная операций отмеченных memory_order_relaxed обладать следующими свойствами:
Original:
Atomic operations tagged 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.
  • Нет упорядочение других обращений к памяти обеспечивается бы то ни было. Это означает, что это не возможно для синхронизации нескольких потоков с использованием атомарных переменных.
    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.
  • Чтение и запись к атомной сама переменная упорядочены. Как только поток считывает значение, последующее чтение тем же потоком из того же объект не может дать ранее значение.
    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.
Например, с x и y первоначально нулю,
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 = atomic_load_explicit(y, memory_order_relaxed);
atomic_store_explicit(x, r1, memory_order_relaxed);
// Thread 2:
r2 = atomic_load_explicit(x, memory_order_relaxed);
atomic_store_explicit(y, 42, memory_order_relaxed);

Допускается изготовление 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.

[править] Релиз-Потребляйте заказа

Если атомная магазин отмеченных memory_order_release и атомные нагрузки от той же переменной отмеченных memory_order_consume, операции обладают следующими свойствами:
Original:
If an atomic store is tagged memory_order_release and an atomic load from the same variable is tagged 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.
  • Не пишет в поток записи могут быть перераспределены после атомной магазина
    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.
  • Не читает или пишет зависит от величины, полученной от атомного нагрузка может быть заказана до атомной нагрузки. "В зависимости от" означает, что адрес или значение вычисляется из значения атомарных переменных. Эта форма синхронизации между потоками известен как "зависимость упорядочение".
    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.
  • Синхронизация установлена ​​только между потоками освобождения и' потребления той же атомной переменной. Другие темы, можно увидеть различные порядке доступа к памяти, чем один или оба синхронизированы темы.
    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.
  • Синхронизация является транзитивным. То есть, если мы имеем следующую ситуацию:
    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.
  • Тема' выпускает атомарных переменных'.
    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.
  • Тема B потребляет атомарных переменных'.
    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.
  • Атомная переменная B зависит от'.
    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.
  • Тема B релизы атомарных переменных 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.
  • Тема C потребляет или приобретает атомарных переменных 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.
Тогда не только' и B или B и C синхронизируются, но' и C тоже. То есть, все пишет в потоке A, которые были начаты до выхода' гарантированно будут завершены раз поток C отмечает в магазине 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.
На всех основных процессоров, кроме DEC Alpha, зависимость упорядочение происходит автоматически, никаких дополнительных инструкций процессора выдаются для этого режима синхронизации, только некоторые оптимизации компиляторов затронуты (например, компилятор, запрещается совершать спекулятивные нагрузки на объекты, которые участвуют в Зависимость цепи)
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.

[править] Отпустите последовательности

Если некоторые атомные это в магазине освобождены и некоторые другие темы, выполнять операции чтения-модификации-записи на что атомная, "освобождение последовательность" формируется: все темы, которые выполняют чтение-модификация-запись в той же атомной синхронизации с первым потоком и друг друга, даже если они не имеют memory_order_release семантики. Это делает один производитель - несколько ситуаций потребителей невозможно без введения ненужных синхронизацию между отдельными потоками потребительских.
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.

[править] Отпустить-продам заказа

Если атомная магазин отмеченных memory_order_release и атомные нагрузки от той же переменной отмеченных memory_order_acquire, операции обладают следующими свойствами:
Original:
If an atomic store is tagged memory_order_release and an atomic load from the same variable is tagged 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.
  • Не пишет в поток записи могут быть перераспределены после атомной магазина
    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.
  • Нет говорится в потоке, читатель может быть заказана до атомной нагрузки.
    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.
  • Синхронизация установлена ​​только между потоками освобождения и' приобретения той же атомной переменной. Другие темы, можно увидеть различные порядке доступа к памяти, чем один или оба синхронизированы темы.
    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.
  • Синхронизация является транзитивным. То есть, если мы имеем следующую ситуацию:
    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.
  • Тема' выпускает атомарных переменных'.
    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.
  • Тема B потребляет атомарных переменных'.
    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.
  • Тема B релизы атомарных переменных 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.
  • Тема C потребляет или приобретает атомарных переменных 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.
Тогда не только' и B или B и C синхронизируются, но' и C тоже. То есть, все пишет в потоке A, которые были начаты до выхода' гарантированно будут завершены раз поток C отмечает в магазине 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.
На строго упорядоченные системы (x86, SPARC, IBM мэйнфреймов), релиз-продам заказа является автоматическим. Никаких дополнительных инструкций процессора выдаются для этого режима синхронизации, только некоторые оптимизации компиляторов затронуты (например, компилятор запрещено выходить неатомической магазинах прошлом атомных магазине Relase или выполнять неатомической грузов раньше, чем атомная нагрузки приобрести)
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.

[править] Последовательно-согласованных заказа

Если атомная магазин и помечен memory_order_seq_cst и атомные нагрузки от той же переменной отмеченных memory_order_seq_cst, то операции обладают следующими свойствами:
Original:
If an atomic store and an is tagged memory_order_seq_cst and an atomic load from the same variable is tagged 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.
  • Не пишет в поток записи могут быть перераспределены после атомной магазина
    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.
  • Нет говорится в потоке, читатель может быть заказана до атомной нагрузки.
    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.
  • Синхронизация между всеми членами атомарных операций отмеченных std::memory_order_seq_cst. Все темы, используя такие атомарные операции см. тот же порядок доступа к памяти.
    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.
Последовательный порядок необходимо для многих несколько производитель-потребитель несколько ситуаций, когда все потребители должны наблюдать за действиями всех производителей, входящих в том же порядке.
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.
Всего последовательное упорядочение требует полной памяти забор инструкций процессора на всех многоядерных систем. Это может стать узким местом, поскольку она заставляет всех доступ к памяти распространяться на каждую нить.
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.

[править] Отношения с нестабильной

{{{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.

[править] Примеры