Espaços nominais
Variantes
Acções

Modelo de memória

Da cppreference.com
< cpp‎ | language
 
 
Linguagem C++
Tópicos gerais
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Controle de fluxo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Declarações execução condicional
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instruções de iteração
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declarações
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
tipo de alias declaração (C++11)
atributos (C++11)
Conversões
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções membro especiais
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
 
Define a semântica do armazenamento de memória do computador para os propósitos da máquina abstrata C++
Original:
Defines the semantics of computer memory storage for the purpose of the C++ abstract machine
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.
A memória disponível para o programa C++ é uma sequência ou mais de bytes contínuos. Cada byte na memória tem um endereço único
Original:
The memory available to a C++ program is one or more contiguous sequences of bytes. Each byte in memory has a unique address
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.

Índice

[editar] Byte

Um byte é a menor unidade de memória endereçável. Ela é definida como uma sequência contínua de bits, grande o suficiente para manter
Original:
A byte is the smallest addressable unit of memory. It is defined as a contiguous sequence of bits, large enough to hold
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • o valor de qualquer código unitário UTF-8 (256 valores distintos) e de
    Original:
    the value of any UTF-8 code unit (256 distinct values) and of
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
(desde C++14)
Predefinição:mark until c++23
Predefinição:mark since c++23
Similar ao C, C++ suporta bytes de tamanho de 8 bits ou mais
Original:
Similar to C, C++ supports bytes of sizes 8 bits and greater
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.
Os tipos char, unsigned char, e signed char usam um byte para armazenamento e representação do valor. O número de bits em um bytes é acessible como CHAR_BIT ou std::numeric_limits<unsigned char>::digits
Original:
The types char, unsigned char, and signed char use one byte for both storage and value representation. The number of bits in a byte is accessible as CHAR_BIT or std::numeric_limits<unsigned char>::digits
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.

[editar] Endereçamento de memória

Um endereço de memória é
Original:
A memory location is
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • um objeto do tipo scalar (tipo aritmético, tipo ponteiro, tipo enumerado, ou std::nullptr_t)
    Original:
    an object of scalar type (arithmetic type, pointer type, enumeration type, or std::nullptr_t)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • ou a maior sequência contínua de campo de bits de tamanho diferente de zero
    Original:
    or the largest contiguous sequence of bit fields of non-zero length
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Nota: Vários recursos da linguagem, assim como referências e funções virtuais, podem envolver localizações de memória que não são acessíveis ao programa mas são gerenciadas pela implementação
Original:
Note: Various features of the language, such as references and virtual functions, might involve additional memory locations that are not accessible to programs but are managed by the implementation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.
struct S {
    char a;     // memory location #1
    int b : 5;  // memory location #2
    int c : 11, // memory location #2 (continued)
          : 0,
        d : 8;  // memory location #3
    struct {
        int ee : 8; // memory location #4
    } e;
} obj; // The object 'obj' consists of 4 separate memory locations

[editar] Threads e condições de corrida

Uma thread de execução é um fluxo de controle dentro de um programa que é iniciado com a invocação de uma função de alto nível através de std::thread::thread, std::async, ou outro meio
Original:
A thread of execution is a flow of control within a program that begins with the invocation of a top-level function by std::thread::thread, std::async, or other means
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.

Uma thread pode potencialmente acessar qualquer objeto no programa (objetos com automático e thread-local duração de armazenamento podem ainda ser acessadas por outras threads através de ponteiros ou por referência)
Original:
Any thread can potentially access any object in the program (objects with automatic and thread-local storage duration may still be accessed by another thread through a pointer or by reference)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.

Diferentes threads de execução sempre podem acessar (ler e modificar) diferentes endereços de memória concorrentemente, sem interferência e sem requisitos de sincronização
Original:
Different threads of execution are always allowed to access (read and modify) different memory locations concurrently, with no interference and no synchronization requirements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.

Quando a avaliação de uma expressão escreve em um endereço de memória e outra avaliação lê ou modifica o mesmo endereço de memória, as expressões são ditas como conflito. Um programa que tem duas avaliações tem uma condição de corrida a menos que
Original:
When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race unless
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • ambas as avaliações executem na mesma thread ou no mesmo signal handler, ou
    Original:
    both evaluations execute on the same thread or in the same signal handler, or
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • ambas as avaliações conflitantes sejam operações atômicas (veja std::atomic), ou
    Original:
    both conflicting evaluations are atomic operations (see std::atomic), or
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • uma das avaliações conflitantes ocorra-antes (see std::memory_order)
    Original:
    one of the conflicting evaluations happens-before another (see std::memory_order)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Se uma condição de corrida ocorre, o comportamento do programa é indefinido
Original:
If a data race occurs, the behavior of the program is undefined
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.

(

Em particular, uma versão de std::mutex é sincronizado-com, e portanto, a aquisição acontece-antes do mesmo mutex por outra thread, o que torna possível o uso de um mutex de guarda para evitar condições de corrida
Original:
In particular, release of a std::mutex is synchronized-with, and therefore, happens-before acquisition of the same mutex by another thread, which makes it possible to use mutex locks to guard against data races
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
).

int cnt = 0;
auto f = [&]{cnt++;};
std::thread t1{f}, t2{f}, t3{f}; // undefined behavior
std::atomic<int> cnt{0};
auto f = [&]{cnt++;};
std::thread t1{f}, t2{f}, t3{f}; // OK

[editar] Ordem de memória

Quando uma thread le um valor de um endereço de memória, ela pode ver o valor inicial, o valor escrito na mesma thread, ou o valor escrito em outra thread. Veja std::memory_order para detalhes na ordem na qual a escrita feita nas threads se torna visível a outras threads
Original:
When a thread reads a value from a memory location, it may see the initial value, the value written in the same thread, or the value written in another thread. See std::memory_order for details on the order in which writes made from threads become visible to other threads
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
.

[editar] Forward progress

[editar] Obstruction freedom

When only one thread that is not blocked in a standard library function executes an atomic function that is lock-free, that execution is guaranteed to complete (all standard library lock-free operations are obstruction-free)

[editar] Lock freedom

When one or more lock-free atomic functions run concurrently, at least one of them is guaranteed to complete (all standard library lock-free operations are lock-free -- it is the job of the implementation to ensure they cannot be live-locked indefinitely by other threads, such as by continuously stealing the cache line)

[editar] Progress guarantee

In a valid C++ program, every thread eventually does one of the following:

  • terminate
  • makes a call to an I/O library function
  • performs an access through a volatile glvalue
  • performs an atomic operation or a synchronization operation

No thread of execution can execute forever without performing any of these observable behaviors.

Note that it means that a program with endless recursion or endless loop (whether implemented as a for-statement or by looping goto or otherwise) has undefined behavior. This allows the compilers to remove all loops that have no observable behavior, without having to prove that they would eventually terminate.

A thread is said to make progress if it performs one of the execution steps above (I/O, volatile, atomic, or synchronization), blocks in a standard library function, or calls an atomic lock-free function that does not complete because of a non-blocked concurrent thread.

Concurrent forward progress

If a thread offers concurrent forward progress guarantee, it will make progress (as defined above) in finite amount of time, for as long as it has not terminated, regardless of whether other threads (if any) are making progress.

The standard encourages, but doesn't require that the main thread and the threads started by std::thread offer concurrent forward progress guarantee.

Parallel forward progress

If a thread offers parallel forward progress guarantee, the implementation is not required to ensure that the thread will eventually make progress if it has not yet executed any execution step (I/O, volatile, atomic, or synchronization), but once this thread has executed a step, it provides concurrent forward progress guarantees (this rule describes a thread in a thread pool that executes tasks in arbitrary order)

Weakly parallel forward progress

If a thread offers weakly parallel forward progress guarantee, it does not guarantee to eventually make progress, regardless of whether other threads make progress or not.

Such threads can still be guaranteed to make progress by blocking with forward progress guarantee delegation: if a thread P blocks in this manner on the completion of a set of threads S, then at least one thread in S will offer a forward progress guarantee that is same or stronger than P. Once that thread completes, another thread in S will be similarly strengthened. Once the set is empty, P will unblock.

The parallel algorithms from the C++ standard library block with forward progress delegation on the completion of an unspecified set of library-managed threads.

(desde C++17)

[editar] See also

Documentação C para Memory model