<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Padrões de Projetos - MCU &amp; FPGA</title>
	<atom:link href="https://mcu.tec.br/categorias/padroes-de-projetos/feed/" rel="self" type="application/rss+xml" />
	<link>https://mcu.tec.br</link>
	<description>Microcontroladores &#38; FPGA</description>
	<lastBuildDate>Sun, 23 Feb 2025 02:18:13 +0000</lastBuildDate>
	<language>pt-BR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://mcu.tec.br/wp-content/uploads/2025/02/Robo-para-o-site-MCU.tec_.br-512x512-1-150x150.png</url>
	<title>Padrões de Projetos - MCU &amp; FPGA</title>
	<link>https://mcu.tec.br</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Garbage Compactor Pattern</title>
		<link>https://mcu.tec.br/linguagem/c/garbage-compactor-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=garbage-compactor-pattern</link>
		
		<dc:creator><![CDATA[Carlos Delfino]]></dc:creator>
		<pubDate>Sat, 22 Feb 2025 22:47:51 +0000</pubDate>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Padrões de Projetos]]></category>
		<category><![CDATA[Garbage Compactor Pattern]]></category>
		<guid isPermaLink="false">https://mcu.tec.br/?p=106</guid>

					<description><![CDATA[<p>O Garbage Compactor Pattern é um padrão de gerenciamento de memória que reorganiza dinamicamente a alocação de memória para reduzir a fragmentação e garantir blocos contíguos disponíveis para uso. Em sistemas embarcados, onde a memória é um recurso extremamente limitado, esse padrão se torna essencial para maximizar o aproveitamento da RAM e evitar falhas inesperadas devido à fragmentação excessiva.</p>
<p>The post <a href="https://mcu.tec.br/linguagem/c/garbage-compactor-pattern/">Garbage Compactor Pattern</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4d6.png" alt="📖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Origem</strong>: <em>Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems</em> – Bruce Powel Douglass</p>



<h2 class="wp-block-heading"><strong>Resumo (Abstract)</strong></h2>



<p class="wp-block-paragraph">O <strong>Garbage Compactor Pattern</strong> é um padrão de gerenciamento de memória que reorganiza dinamicamente a alocação de memória para reduzir a fragmentação e garantir blocos contíguos disponíveis para uso. Em sistemas embarcados, onde a memória é um recurso extremamente limitado, esse padrão se torna essencial para maximizar o aproveitamento da RAM e evitar falhas inesperadas devido à fragmentação excessiva.</p>



<h2 class="wp-block-heading"><strong>Problema a ser resolvido</strong></h2>



<p class="wp-block-paragraph">Sistemas que fazem uso de alocação dinâmica de memória frequentemente sofrem com a fragmentação, onde blocos livres são dispersos na RAM, impossibilitando a alocação de grandes blocos de memória mesmo quando há espaço suficiente disponível. Esse problema é particularmente crítico em sistemas embarcados, onde a memória é limitada e cada falha na alocação pode levar a travamentos, reinicializações ou falhas de desempenho.</p>



<p class="wp-block-paragraph">Além disso, a fragmentação pode tornar os tempos de resposta imprevisíveis, pois a busca por blocos de memória disponíveis se torna mais complexa. Sistemas de tempo real precisam de garantias de tempo de resposta determinístico, algo que pode ser comprometido caso a fragmentação cause variações no tempo de alocação. O <strong>Garbage Compactor Pattern</strong> resolve esse problema ao reorganizar periodicamente a memória, consolidando blocos livres em regiões contínuas e garantindo que grandes alocações possam ser feitas sem falhas.</p>



<h2 class="wp-block-heading"><strong>Estrutura do Padrão</strong></h2>



<p class="wp-block-paragraph">A estrutura desse padrão envolve um <strong>gerenciador de heap</strong>, que monitora a fragmentação da memória e decide quando realizar a compactação. A <strong>lista de blocos ocupados</strong> rastreia quais segmentos da RAM estão em uso, enquanto a <strong>lista de blocos livres</strong> gerencia os espaços disponíveis. Um <strong>mecanismo de realocação</strong> move os dados dos blocos alocados para consolidar as áreas livres, garantindo que a memória seja reorganizada sem impactar o funcionamento do sistema.</p>



<p class="wp-block-paragraph">A compactação pode ser realizada em momentos estratégicos, como durante períodos de baixa atividade do sistema ou quando a fragmentação atinge um limite crítico. Esse processo pode ser implementado de forma assíncrona para minimizar impactos no desempenho.</p>



<h2 class="wp-block-heading"><strong>Papéis de Colaboração (Collaborations Roles)</strong></h2>



<ul class="wp-block-list">
<li><strong>Gerenciador de Heap</strong>: Supervisiona a alocação, desalocação e reorganização dos blocos de memória.</li>



<li><strong>Lista de Blocos Ocupados</strong>: Mantém um mapeamento dos blocos de memória em uso.</li>



<li><strong>Lista de Blocos Livres</strong>: Armazena informações sobre os segmentos disponíveis para alocação.</li>



<li><strong>Mecanismo de Realocação</strong>: Move os dados entre os blocos de memória para consolidar áreas livres.</li>



<li><strong>Cliente</strong>: Solicita alocações e liberações de memória conforme necessário.</li>



<li><strong>Segmento de Memória</strong>: Contém a memória real onde os blocos são armazenados e reorganizados.</li>
</ul>



<h2 class="wp-block-heading"><strong>Consequências</strong></h2>



<p class="wp-block-paragraph">A aplicação do <strong>Garbage Compactor Pattern</strong> traz benefícios significativos para sistemas embarcados. Ele melhora a eficiência do uso da memória, garantindo que grandes blocos possam ser alocados sem falhas. Além disso, reduz os tempos de busca por espaço livre, melhorando a previsibilidade dos tempos de resposta, algo essencial em sistemas de tempo real.</p>



<p class="wp-block-paragraph">Por outro lado, o processo de compactação pode ser custoso em termos de processamento, pois requer movimentação de dados na RAM. Se não for gerenciado corretamente, pode causar pausas no sistema que impactam a responsividade da aplicação. Outra consideração importante é que a movimentação dos blocos pode exigir a atualização de ponteiros e referências, o que pode ser complexo em algumas arquiteturas.</p>



<h2 class="wp-block-heading"><strong>Estratégias de Implementação</strong></h2>



<p class="wp-block-paragraph">A implementação do <strong>Garbage Compactor Pattern</strong> pode seguir diferentes abordagens, dependendo dos requisitos do sistema. Uma estratégia comum é a <strong>compactação periódica</strong>, onde a reorganização da memória ocorre em intervalos regulares ou quando a fragmentação atinge um limite predefinido. Esse método é útil em sistemas onde há momentos de baixa carga que podem ser aproveitados para a reorganização da memória.</p>



<p class="wp-block-paragraph">Outra abordagem é a <strong>compactação sob demanda</strong>, onde a reorganização ocorre apenas quando uma tentativa de alocação falha devido à fragmentação. Essa estratégia minimiza o impacto no desempenho, pois a compactação é realizada apenas quando necessário. No entanto, pode causar atrasos inesperados no tempo de resposta quando a compactação precisa ser feita em um momento crítico.</p>



<p class="wp-block-paragraph">Para garantir a integridade dos dados durante a realocação, é essencial utilizar <strong>mecanismos de proteção de ponteiros</strong>, garantindo que referências a blocos de memória sejam atualizadas corretamente. Outra técnica útil é a utilização de <strong>buffers temporários</strong>, permitindo que dados sejam copiados para uma área intermediária antes de serem reposicionados.</p>



<h2 class="wp-block-heading"><strong>Padrões Relacionados</strong></h2>



<p class="wp-block-paragraph">O <strong>Garbage Compactor Pattern</strong> está diretamente relacionado a outros padrões de gerenciamento de memória:</p>



<ul class="wp-block-list">
<li><strong><a href="https://mcu.tec.br/linguagem/c/pool-allocation-pattern/" title="Pool Allocation Pattern">Pool Allocation Pattern</a></strong>: Ambos lidam com otimização do uso de memória, mas o Pool Allocation evita a fragmentação desde o início, enquanto o Garbage Compactor atua quando a fragmentação já ocorreu.</li>



<li><strong><a href="https://mcu.tec.br/padroes-de-projetos/fixed-sized-buffer-pattern/" title="Fixed-Sized Buffer Pattern">Fixed-Sized Buffer Pattern</a></strong>: Pode ser combinado com a compactação de memória para garantir um uso mais eficiente da RAM.</li>



<li><strong>Priority Ceiling Pattern</strong>: Pode ser usado para garantir que o processo de compactação ocorra sem interrupções indesejadas em sistemas críticos.</li>



<li><strong>Critical Section Pattern</strong>: Pode ser necessário para evitar acessos concorrentes durante a compactação.</li>
</ul>



<h2 class="wp-block-heading"><strong>Modelo de Amostragem (Exemplo de Código)</strong></h2>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="617" src="https://mcu.tec.br/wp-content/uploads/2025/02/image-3-1024x617.png" alt="" class="wp-image-110" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/image-3-1024x617.png 1024w, https://mcu.tec.br/wp-content/uploads/2025/02/image-3-300x181.png 300w, https://mcu.tec.br/wp-content/uploads/2025/02/image-3-768x463.png 768w, https://mcu.tec.br/wp-content/uploads/2025/02/image-3-1536x925.png 1536w, https://mcu.tec.br/wp-content/uploads/2025/02/image-3-2048x1234.png 2048w, https://mcu.tec.br/wp-content/uploads/2025/02/image-3-240x145.png 240w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph">Segue um exemplo de implementação simplificada do <strong>Garbage Compactor Pattern</strong> em C:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#2e3440ff"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdint.h&gt;
#include &lt;stdbool.h&gt;
#include &lt;string.h&gt;

#define HEAP_SIZE 1024  // Tamanho total do heap
#define BLOCK_SIZE 32    // Tamanho de cada bloco de memória
#define NUM_BLOCKS (HEAP_SIZE / BLOCK_SIZE)

typedef struct MemoryBlock {
    bool in_use;
    void *ptr;
    size_t size;
} MemoryBlock;

typedef struct Segment {
    MemoryBlock blocks[NUM_BLOCKS];
    uint8_t memory[HEAP_SIZE];
    struct Segment *next;
} Segment;

typedef struct BufferedPtr {
    void **ptr;
} BufferedPtr;

typedef struct GarbageCompactor {
    Segment *activeSegment;
    Segment *inactiveSegment;
} GarbageCompactor;

Segment segment1, segment2;
GarbageCompactor gc;

void init_segments() {
    memset(&amp;segment1, 0, sizeof(Segment));
    memset(&amp;segment2, 0, sizeof(Segment));
    gc.activeSegment = &segment1;
    gc.inactiveSegment = &segment2;
}

void *allocate_memory(size_t size) {
    Segment *seg = gc.activeSegment;
    for (int i = 0; i &lt; NUM_BLOCKS; i++) {
        if (!seg-&gt;blocks[i].in
" style="color:#d8dee9ff;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki nord" style="background-color: #2e3440ff" tabindex="0"><code><span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdio.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdlib.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdint.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdbool.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">string.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">HEAP_SIZE</span><span style="color: #5E81AC"> </span><span style="color: #B48EAD">1024</span><span style="color: #616E88">  // Tamanho total do heap</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">BLOCK_SIZE</span><span style="color: #5E81AC"> </span><span style="color: #B48EAD">32</span><span style="color: #616E88">    // Tamanho de cada bloco de memória</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">NUM_BLOCKS</span><span style="color: #5E81AC"> </span><span style="color: #ECEFF4">(</span><span style="color: #5E81AC">HEAP_SIZE </span><span style="color: #81A1C1">/</span><span style="color: #5E81AC"> BLOCK_SIZE</span><span style="color: #ECEFF4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> MemoryBlock </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">bool</span><span style="color: #D8DEE9FF"> in_use</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF">ptr</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">size_t</span><span style="color: #D8DEE9FF"> size</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> MemoryBlock</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> Segment </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    MemoryBlock blocks</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">NUM_BLOCKS</span><span style="color: #ECEFF4">]</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">uint8_t</span><span style="color: #D8DEE9FF"> memory</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">HEAP_SIZE</span><span style="color: #ECEFF4">]</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> Segment </span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF">next</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> Segment</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> BufferedPtr </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">**</span><span style="color: #D8DEE9FF">ptr</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> BufferedPtr</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> GarbageCompactor </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    Segment </span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF">activeSegment</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    Segment </span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF">inactiveSegment</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> GarbageCompactor</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D8DEE9FF">Segment segment1</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> segment2</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">GarbageCompactor gc</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">init_segments</span><span style="color: #ECEFF4">()</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">memset</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">segment1</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">sizeof</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">Segment</span><span style="color: #ECEFF4">))</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">memset</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">segment2</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">sizeof</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">Segment</span><span style="color: #ECEFF4">))</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #D8DEE9">gc</span><span style="color: #ECEFF4">.</span><span style="color: #D8DEE9">activeSegment</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">segment1</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #D8DEE9">gc</span><span style="color: #ECEFF4">.</span><span style="color: #D8DEE9">inactiveSegment</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">segment2</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">*</span><span style="color: #88C0D0">allocate_memory</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">size_t</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">size</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    Segment </span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF">seg </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">gc</span><span style="color: #ECEFF4">.</span><span style="color: #D8DEE9">activeSegment</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">for</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">int</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">&lt;</span><span style="color: #D8DEE9FF"> NUM_BLOCKS</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i</span><span style="color: #81A1C1">++</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">!</span><span style="color: #D8DEE9">seg</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">blocks</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">i</span><span style="color: #ECEFF4">].</span><span style="color: #D8DEE9">in</span></span>
<span class="line"></span></code></pre></div><p>The post <a href="https://mcu.tec.br/linguagem/c/garbage-compactor-pattern/">Garbage Compactor Pattern</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">106</post-id>	</item>
		<item>
		<title>Pool Allocation Pattern</title>
		<link>https://mcu.tec.br/linguagem/c/pool-allocation-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pool-allocation-pattern</link>
		
		<dc:creator><![CDATA[Carlos Delfino]]></dc:creator>
		<pubDate>Sat, 22 Feb 2025 21:55:06 +0000</pubDate>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Padrões de Projetos]]></category>
		<category><![CDATA[Pool Allocation Pattern]]></category>
		<guid isPermaLink="false">https://mcu.tec.br/?p=103</guid>

					<description><![CDATA[<p>O Pool Allocation Pattern é um padrão que gerencia a memória de forma eficiente ao pré-alocar blocos de tamanho fixo para reutilização. Ele resolve problemas comuns da alocação dinâmica, como fragmentação e imprevisibilidade no tempo de acesso, tornando-se essencial para sistemas embarcados e de tempo real. Esse padrão melhora a eficiência do uso da RAM ao garantir que blocos de memória sejam reutilizados conforme necessário, sem necessidade de alocações dinâmicas constantes.</p>
<p>The post <a href="https://mcu.tec.br/linguagem/c/pool-allocation-pattern/">Pool Allocation Pattern</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4d6.png" alt="📖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Origem</strong>: <em>Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems</em> – Bruce Powel Douglass</p>



<h2 class="wp-block-heading"><strong>Resumo</strong></h2>



<p class="wp-block-paragraph">O <strong>Pool Allocation Pattern</strong> é um padrão que gerencia a memória de forma eficiente ao pré-alocar blocos de tamanho fixo para reutilização. Ele resolve problemas comuns da alocação dinâmica, como fragmentação e imprevisibilidade no tempo de acesso, tornando-se essencial para sistemas embarcados e de tempo real. Esse padrão melhora a eficiência do uso da RAM ao garantir que blocos de memória sejam reutilizados conforme necessário, sem necessidade de alocações dinâmicas constantes.</p>



<h2 class="wp-block-heading"><strong>Problema a ser resolvido</strong></h2>



<p class="wp-block-paragraph">A alocação dinâmica de memória (<code>malloc()</code> e <code>free()</code>) pode levar à fragmentação e latências imprevisíveis, o que é inaceitável para sistemas embarcados de tempo real. Além disso, quando a memória se esgota ou está altamente fragmentada, pode ocorrer falha na alocação de novos blocos, resultando em comportamento inesperado do sistema.</p>



<p class="wp-block-paragraph">Outro problema comum é a sobrecarga de gerenciamento de memória, onde a alocação e desalocação frequente de pequenos blocos gera um overhead significativo. Isso reduz a eficiência do sistema e pode impactar o tempo de resposta em aplicações críticas. Em sistemas embarcados com recursos limitados, é crucial garantir que a memória seja usada de forma previsível e eficiente.</p>



<p class="wp-block-paragraph">O <strong>Pool Allocation Pattern</strong> resolve esses problemas ao manter um conjunto fixo de blocos de memória pré-alocados, permitindo que o sistema reutilize esses blocos de maneira eficiente. Isso elimina a necessidade de alocação e desalocação dinâmica, garantindo tempos de resposta constantes e previsíveis.</p>



<h2 class="wp-block-heading"><strong>Estrutura do Padrão</strong></h2>



<p class="wp-block-paragraph">A estrutura desse padrão se baseia em um <strong>gerenciador de pool de memória</strong>, que mantém uma <strong>lista de blocos livres</strong> prontos para serem usados. Cada bloco tem um tamanho fixo e pode ser alocado rapidamente sem a necessidade de recorrer ao heap. A <strong>fábrica de objetos</strong> pode ser usada para criar e inicializar os blocos, enquanto um <strong>gerenciador de heap dimensionado</strong> garante que os blocos sejam usados de maneira eficiente.</p>



<p class="wp-block-paragraph">Os dados são armazenados no <strong>segmento de memória</strong>, garantindo que a RAM seja utilizada de forma previsível. O acesso ao pool pode ser gerenciado por mecanismos como filas FIFO (First In, First Out) ou LIFO (Last In, First Out), dependendo das necessidades da aplicação.</p>



<h2 class="wp-block-heading"><strong>Papéis de Colaboração</strong></h2>



<ul class="wp-block-list">
<li><strong>Cliente</strong>: Solicita e libera blocos de memória conforme necessário.</li>



<li><strong>Lista de Blocos Livres</strong>: Mantém o controle dos blocos de memória disponíveis para reutilização.</li>



<li><strong>Gerenciador de Pool</strong>: Supervisiona a alocação e liberação dos blocos, garantindo que a memória seja usada eficientemente.</li>



<li><strong>Segmento de Memória</strong>: Armazena fisicamente os blocos alocados.</li>



<li><strong>Fábrica de Objetos</strong>: Pode ser usada para criar instâncias de objetos que utilizam a alocação por pool.</li>



<li><strong>Heap Dimensionado</strong>: Garante que os blocos tenham um tamanho fixo e que a memória seja utilizada de maneira eficiente.</li>
</ul>



<h2 class="wp-block-heading"><strong>Consequências</strong></h2>



<p class="wp-block-paragraph">O <strong>Pool Allocation Pattern</strong> traz diversas vantagens para sistemas embarcados. Ele reduz drasticamente o tempo de alocação de memória, pois os blocos já estão pré-alocados e prontos para uso. Isso melhora o tempo de resposta do sistema e evita problemas de fragmentação. Além disso, ao reutilizar blocos já existentes, o padrão reduz a necessidade de operações de gerenciamento de heap, economizando processamento.</p>



<p class="wp-block-paragraph">Entretanto, esse padrão pode levar ao desperdício de memória se o número de blocos pré-alocados for maior do que o necessário. Se a quantidade de blocos for insuficiente, pode ser necessário um mecanismo de fallback para lidar com situações onde não há memória disponível. Além disso, a implementação deve ser bem planejada para evitar vazamentos de memória devido a blocos que não são liberados corretamente.</p>



<h2 class="wp-block-heading"><strong>Estratégias de Implementação</strong></h2>



<p class="wp-block-paragraph">Para implementar o <strong>Pool Allocation Pattern</strong>, um array de blocos de memória é criado no momento da inicialização do sistema. Um gerenciador de pool mantém uma lista encadeada de blocos disponíveis, permitindo alocação e liberação rápidas. Em sistemas que exigem eficiência máxima, um <strong>buffer circular</strong> pode ser utilizado para gerenciar os blocos de forma ainda mais eficiente.</p>



<p class="wp-block-paragraph">A implementação pode incluir verificações para evitar acessos indevidos a blocos não alocados. Além disso, em sistemas multitarefa, mutexes ou semáforos podem ser usados para garantir que múltiplas tarefas acessem o pool de maneira segura. Em casos onde há necessidade de realocação dinâmica, pode-se combinar esse padrão com o <strong>Fixed-Sized Buffer Pattern</strong>, garantindo que cada bloco tenha um tamanho fixo e previsível.</p>



<h2 class="wp-block-heading"><strong>Padrões Relacionados</strong></h2>



<p class="wp-block-paragraph">O <strong>Pool Allocation Pattern</strong> está diretamente relacionado a outros padrões de gerenciamento de memória e sincronização:</p>



<ul class="wp-block-list">
<li><strong><a href="https://mcu.tec.br/padroes-de-projetos/fixed-sized-buffer-pattern/" title="Fixed-Sized Buffer Pattern">Fixed-Sized Buffer Pattern</a></strong>: Ambos evitam alocação dinâmica e melhoram a previsibilidade do uso da memória.</li>



<li><strong>Message Queuing Pattern</strong>: Pode ser usado em conjunto para gerenciar filas de mensagens sem consumir memória excessiva.</li>



<li><strong>Garbage Compactor Pattern</strong>: Pode ser útil quando há necessidade de reorganizar a memória para evitar fragmentação.</li>



<li><strong>Critical Section Pattern</strong>: Pode ser necessário para evitar acesso concorrente a blocos do pool.</li>
</ul>



<h2 class="wp-block-heading"><strong>Modelo de Amostragem (Exemplo de Código)</strong></h2>



<p class="wp-block-paragraph">Aqui está um exemplo de implementação do <strong>Pool Allocation Pattern</strong> em C:</p>



<p class="wp-block-paragraph"></p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#2e3440ff"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="#include &lt;stdio.h&gt;
#include &lt;stdint.h&gt;

#define POOL_SIZE 1000 // Número máximo de objetos TempData

// Estrutura de dados de temperatura
typedef struct {
    int id;
    float temperature;
} TempData;

// Estrutura para o Pool de Recursos
typedef struct {
    TempData pool[POOL_SIZE];  // Array de objetos
    uint8_t allocated[POOL_SIZE];  // Flags para indicar quais objetos estão em uso
} TempDataPool;

// Inicializa o pool de dados
void initPool(TempDataPool* pool) {
    for (int i = 0; i &lt; POOL_SIZE; i++) {
        pool-&gt;allocated[i] = 0;  // Nenhum objeto está alocado inicialmente
    }
}

// Aloca um objeto TempData do pool
TempData* allocateTempData(TempDataPool* pool) {
    for (int i = 0; i &lt; POOL_SIZE; i++) {
        if (!pool-&gt;allocated[i]) {  // Se não estiver em uso
            pool-&gt;allocated[i] = 1; // Marca como alocado
            return &amp;pool-&gt;pool[i];
        }
    }
    return NULL; // Pool esgotado
}

// Libera um objeto TempData e o devolve ao pool
void releaseTempData(TempDataPool* pool, TempData* data) {
    int index = data - pool-&gt;pool;  // Calcula o índice do objeto
    if (index &gt;= 0 &amp;&amp; index &lt; POOL_SIZE) {
        pool-&gt;allocated[index] = 0; // Marca como livre
    }
}

// Simulação de sensores e histórico
void simulateUsage() {
    TempDataPool tempPool;
    initPool(&amp;tempPool);

    TempData* temp1 = allocateTempData(&amp;tempPool);
    if (temp1) {
        temp1-&gt;id = 1;
        temp1-&gt;temperature = 23.5;
        printf(&quot;TempData %d alocado: %.2f°C\n&quot;, temp1-&gt;id, temp1-&gt;temperature);
    }

    TempData* temp2 = allocateTempData(&amp;tempPool);
    if (temp2) {
        temp2-&gt;id = 2;
        temp2-&gt;temperature = 24.0;
        printf(&quot;TempData %d alocado: %.2f°C\n&quot;, temp2-&gt;id, temp2-&gt;temperature);
    }

    releaseTempData(&amp;tempPool, temp1);
    printf(&quot;TempData %d liberado\n&quot;, temp1-&gt;id);

    TempData* temp3 = allocateTempData(&amp;tempPool);
    if (temp3) {
        temp3-&gt;id = 3;
        temp3-&gt;temperature = 22.8;
        printf(&quot;TempData %d alocado: %.2f°C\n&quot;, temp3-&gt;id, temp3-&gt;temperature);
    }
}

int main() {
    simulateUsage();
    return 0;
}
" style="color:#d8dee9ff;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki nord" style="background-color: #2e3440ff" tabindex="0"><code><span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdio.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdint.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">POOL_SIZE</span><span style="color: #5E81AC"> </span><span style="color: #B48EAD">1000</span><span style="color: #616E88"> // Número máximo de objetos TempData</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Estrutura de dados de temperatura</span></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">int</span><span style="color: #D8DEE9FF"> id</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">float</span><span style="color: #D8DEE9FF"> temperature</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> TempData</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Estrutura para o Pool de Recursos</span></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    TempData pool</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">POOL_SIZE</span><span style="color: #ECEFF4">]</span><span style="color: #81A1C1">;</span><span style="color: #616E88">  // Array de objetos</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">uint8_t</span><span style="color: #D8DEE9FF"> allocated</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">POOL_SIZE</span><span style="color: #ECEFF4">]</span><span style="color: #81A1C1">;</span><span style="color: #616E88">  // Flags para indicar quais objetos estão em uso</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> TempDataPool</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Inicializa o pool de dados</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">initPool</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">TempDataPool</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">pool</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">for</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">int</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">&lt;</span><span style="color: #D8DEE9FF"> POOL_SIZE</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i</span><span style="color: #81A1C1">++</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">pool</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">allocated</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">i</span><span style="color: #ECEFF4">]</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #81A1C1">;</span><span style="color: #616E88">  // Nenhum objeto está alocado inicialmente</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Aloca um objeto TempData do pool</span></span>
<span class="line"><span style="color: #D8DEE9FF">TempData</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocateTempData</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">TempDataPool</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">pool</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">for</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">int</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">&lt;</span><span style="color: #D8DEE9FF"> POOL_SIZE</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i</span><span style="color: #81A1C1">++</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">!</span><span style="color: #D8DEE9">pool</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">allocated</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">i</span><span style="color: #ECEFF4">])</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span><span style="color: #616E88">  // Se não estiver em uso</span></span>
<span class="line"><span style="color: #D8DEE9FF">            </span><span style="color: #D8DEE9">pool</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">allocated</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">i</span><span style="color: #ECEFF4">]</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">1</span><span style="color: #81A1C1">;</span><span style="color: #616E88"> // Marca como alocado</span></span>
<span class="line"><span style="color: #D8DEE9FF">            </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9">pool</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">pool</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">i</span><span style="color: #ECEFF4">]</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">NULL;</span><span style="color: #616E88"> // Pool esgotado</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Libera um objeto TempData e o devolve ao pool</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">releaseTempData</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">TempDataPool</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">pool</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> TempData</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">data</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">int</span><span style="color: #D8DEE9FF"> index </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> data </span><span style="color: #81A1C1">-</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">pool</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">pool</span><span style="color: #81A1C1">;</span><span style="color: #616E88">  // Calcula o índice do objeto</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">index </span><span style="color: #81A1C1">&gt;=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">&amp;&amp;</span><span style="color: #D8DEE9FF"> index </span><span style="color: #81A1C1">&lt;</span><span style="color: #D8DEE9FF"> POOL_SIZE</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">pool</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">allocated</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">index</span><span style="color: #ECEFF4">]</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #81A1C1">;</span><span style="color: #616E88"> // Marca como livre</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Simulação de sensores e histórico</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">simulateUsage</span><span style="color: #ECEFF4">()</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    TempDataPool tempPool</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">initPool</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">tempPool</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D8DEE9FF">    TempData</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> temp1 </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocateTempData</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">tempPool</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">temp1</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">temp1</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">id</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">1</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">temp1</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">temperature</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">23.5</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #88C0D0">printf</span><span style="color: #ECEFF4">(</span><span style="color: #ECEFF4">&quot;</span><span style="color: #A3BE8C">TempData %d alocado: %.2f°C</span><span style="color: #EBCB8B">\n</span><span style="color: #ECEFF4">&quot;</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">temp1</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">id</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">temp1</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">temperature</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D8DEE9FF">    TempData</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> temp2 </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocateTempData</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">tempPool</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">temp2</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">temp2</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">id</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">2</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">temp2</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">temperature</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">24.0</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #88C0D0">printf</span><span style="color: #ECEFF4">(</span><span style="color: #ECEFF4">&quot;</span><span style="color: #A3BE8C">TempData %d alocado: %.2f°C</span><span style="color: #EBCB8B">\n</span><span style="color: #ECEFF4">&quot;</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">temp2</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">id</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">temp2</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">temperature</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">releaseTempData</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">tempPool</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> temp1</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">printf</span><span style="color: #ECEFF4">(</span><span style="color: #ECEFF4">&quot;</span><span style="color: #A3BE8C">TempData %d liberado</span><span style="color: #EBCB8B">\n</span><span style="color: #ECEFF4">&quot;</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">temp1</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">id</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D8DEE9FF">    TempData</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> temp3 </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocateTempData</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">tempPool</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">temp3</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">temp3</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">id</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">3</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">temp3</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">temperature</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">22.8</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #88C0D0">printf</span><span style="color: #ECEFF4">(</span><span style="color: #ECEFF4">&quot;</span><span style="color: #A3BE8C">TempData %d alocado: %.2f°C</span><span style="color: #EBCB8B">\n</span><span style="color: #ECEFF4">&quot;</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">temp3</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">id</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">temp3</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">temperature</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">int</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">main</span><span style="color: #ECEFF4">()</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">simulateUsage</span><span style="color: #ECEFF4">()</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span></code></pre></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Abaixo segue o diagrama Estrutural:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="813" src="https://mcu.tec.br/wp-content/uploads/2025/02/image-1-1024x813.png" alt="" class="wp-image-104" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/image-1-1024x813.png 1024w, https://mcu.tec.br/wp-content/uploads/2025/02/image-1-300x238.png 300w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Diagrama Estrutural</figcaption></figure>



<p class="wp-block-paragraph">A seguir o diagrama de sequência:</p><p>The post <a href="https://mcu.tec.br/linguagem/c/pool-allocation-pattern/">Pool Allocation Pattern</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">103</post-id>	</item>
		<item>
		<title>Fixed-Sized Buffer Pattern</title>
		<link>https://mcu.tec.br/padroes-de-projetos/fixed-sized-buffer-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=fixed-sized-buffer-pattern</link>
		
		<dc:creator><![CDATA[Carlos Delfino]]></dc:creator>
		<pubDate>Sat, 22 Feb 2025 18:21:47 +0000</pubDate>
				<category><![CDATA[Padrões de Projetos]]></category>
		<guid isPermaLink="false">https://mcu.tec.br/?p=95</guid>

					<description><![CDATA[<p>📖 Origem: Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems – Bruce Powel Douglass Resumo O Fixed-Sized Buffer Pattern é um padrão de gerenciamento de memória que utiliza buffers de tamanho fixo e pré-alocados para armazenar dados temporários em sistemas embarcados. Ele é amplamente utilizado para comunicação entre módulos do sistema, filas de mensagens, [&#8230;]</p>
<p>The post <a href="https://mcu.tec.br/padroes-de-projetos/fixed-sized-buffer-pattern/">Fixed-Sized Buffer Pattern</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4d6.png" alt="📖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Origem</strong>: <em>Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems</em> – Bruce Powel Douglass</p>



<h2 class="wp-block-heading"><strong>Resumo</strong></h2>



<p class="wp-block-paragraph">O <strong>Fixed-Sized Buffer Pattern</strong> é um padrão de gerenciamento de memória que utiliza buffers de tamanho fixo e pré-alocados para armazenar dados temporários em sistemas embarcados. Ele é amplamente utilizado para comunicação entre módulos do sistema, filas de mensagens, buffers de entrada e saída e armazenamento intermediário de dados. A sua principal vantagem é a previsibilidade do uso da memória, evitando fragmentação e problemas de desempenho associados à alocação dinâmica. Esse padrão se mostra essencial para sistemas de tempo real, onde a confiabilidade da memória é um fator crítico.</p>



<h2 class="wp-block-heading"><strong>Problema a ser resolvido</strong></h2>



<p class="wp-block-paragraph">Muitos sistemas embarcados precisam armazenar temporariamente dados antes de processá-los. Isso pode ocorrer, por exemplo, em buffers de recepção de comunicação serial, aquisição de sinais analógicos ou manipulação de pacotes de rede. A alocação dinâmica de memória, como o uso de <code>malloc()</code> e <code>free()</code>, pode levar à fragmentação e falhas inesperadas, além de introduzir latências imprevisíveis que prejudicam o desempenho em aplicações de tempo real.</p>



<p class="wp-block-paragraph">Outro problema comum ocorre quando buffers de tamanho variável são usados, pois isso dificulta a previsão do consumo de RAM. Em sistemas embarcados, onde cada byte de memória é valioso, a má gestão desses buffers pode levar a desperdício de memória ou esgotamento precoce dos recursos disponíveis. Além disso, sistemas que dependem de alocação dinâmica podem sofrer falhas catastróficas caso a memória se esgote durante a execução, causando travamentos ou reinicializações inesperadas.</p>



<p class="wp-block-paragraph">O <strong>Fixed-Sized Buffer Pattern</strong> resolve esses problemas ao pré-alocar um buffer de tamanho fixo, garantindo um consumo de memória estável e previsível. Dessa forma, evita-se a fragmentação e garante-se um tempo de acesso constante aos dados, permitindo que sistemas críticos operem sem interrupções.</p>



<h2 class="wp-block-heading"><strong>Estrutura do Padrão</strong></h2>



<p class="wp-block-paragraph">A estrutura do padrão se baseia na alocação de um bloco de memória de tamanho fixo no momento da inicialização do sistema. Esse bloco pode ser organizado como um array circular ou uma lista estática de elementos. O gerenciamento do buffer é feito por índices ou ponteiros que controlam a posição de leitura e escrita, garantindo que os dados sejam armazenados e recuperados de forma ordenada.</p>



<p class="wp-block-paragraph">Além da estrutura principal do buffer, há também um <strong>gerenciador de heap</strong>, que pode ser responsável por distribuir múltiplos buffers conforme a necessidade da aplicação. A <strong>lista de blocos livres</strong> mantém o controle sobre quais partes do buffer estão disponíveis para escrita, evitando sobrescrita acidental. Já o <strong>segmento de memória</strong> contém o espaço físico onde os dados são armazenados.</p>



<p class="wp-block-paragraph">Outros elementos importantes incluem a <strong>fábrica de objetos</strong>, que pode criar e liberar instâncias de buffers conforme necessário, e o <strong>heap dimensionado</strong>, que garante que os buffers alocados tenham um tamanho predefinido e constante.</p>



<h2 class="wp-block-heading"><strong>Papéis de Colaboração</strong></h2>



<ul class="wp-block-list">
<li><strong>Cliente</strong>: Solicita espaço no buffer para armazenar dados e recuperá-los posteriormente.</li>



<li><strong>Produtor</strong>: Responsável por inserir dados no buffer, como sensores, módulos de comunicação ou periféricos.</li>



<li><strong>Consumidor</strong>: Recupera os dados armazenados no buffer para processamento ou transmissão.</li>



<li><strong>Lista de Blocos Livres</strong>: Mantém um registro das áreas disponíveis no buffer para novas alocações.</li>



<li><strong>Gerenciador de Heap</strong>: Supervisiona a alocação e reutilização dos buffers de tamanho fixo.</li>



<li><strong>Segmento de Memória</strong>: Armazena fisicamente os dados dentro do buffer pré-alocado.</li>



<li><strong>Fábrica de Objetos</strong>: Pode ser usada para criar instâncias de buffers conforme a demanda do sistema.</li>



<li><strong>Heap Dimensionado</strong>: Assegura que os buffers tenham tamanhos predefinidos e não sofram alterações durante a execução.</li>
</ul>



<h2 class="wp-block-heading"><strong>Consequências</strong></h2>



<p class="wp-block-paragraph">O <strong>Fixed-Sized Buffer Pattern</strong> oferece diversas vantagens. Ele elimina a necessidade de alocação dinâmica de memória, reduzindo riscos de fragmentação e falhas inesperadas. Além disso, por definir um tamanho fixo para os buffers, o consumo de RAM é altamente previsível, permitindo que o sistema seja otimizado para uso eficiente dos recursos. Esse padrão também melhora a performance, pois evita as operações de alocação e desalocação que podem introduzir latências imprevisíveis.</p>



<p class="wp-block-paragraph">Por outro lado, esse padrão pode levar a um certo desperdício de memória caso o tamanho do buffer seja superdimensionado. Se o buffer for maior do que necessário, a memória será ocupada sem ser utilizada de forma eficiente. Além disso, em sistemas com múltiplos buffers, pode ser necessário um mecanismo adicional para garantir a reutilização adequada das áreas de memória.</p>



<h2 class="wp-block-heading"><strong>Estratégias de Implementação</strong></h2>



<p class="wp-block-paragraph">Uma das formas mais comuns de implementar esse padrão é através de <strong>buffers circulares</strong>, onde os dados são armazenados em um array fixo e os índices de leitura e escrita são atualizados continuamente. Isso permite que o buffer seja reutilizado sem a necessidade de realocação de memória. Outra abordagem é utilizar <strong>listas de blocos fixos</strong>, onde cada bloco é tratado como uma unidade independente de armazenamento.</p>



<p class="wp-block-paragraph">Para garantir acesso seguro ao buffer em sistemas multitarefa, pode ser necessário o uso de mutexes ou semáforos para evitar condições de corrida. Outra estratégia comum é implementar verificações de integridade no buffer, como a adição de checksums para detectar corrupção de dados. Em alguns casos, pode ser interessante combinar esse padrão com o <strong>Priority Ceiling Pattern</strong>, garantindo que tarefas críticas tenham acesso prioritário ao buffer.</p>



<h2 class="wp-block-heading"><strong>Padrões Relacionados</strong></h2>



<p class="wp-block-paragraph">O <strong>Fixed-Sized Buffer Pattern</strong> possui uma forte relação com outros padrões de gerenciamento de memória e comunicação:</p>



<ul class="wp-block-list">
<li><strong>Pool Allocation Pattern</strong>: Ambos utilizam blocos de memória predefinidos para evitar fragmentação.</li>



<li><strong>Message Queuing Pattern</strong>: Pode utilizar buffers fixos para armazenar mensagens temporárias antes de processá-las.</li>



<li><strong>Critical Section Pattern</strong>: Pode ser necessário para evitar condições de corrida ao acessar buffers compartilhados.</li>



<li><strong>Garbage Compactor Pattern</strong>: Pode ser útil em sistemas que precisam reorganizar a memória quando múltiplos buffers são usados.</li>
</ul>



<h2 class="wp-block-heading"><strong>Exemplo de Código</strong></h2>



<p class="wp-block-paragraph">Aqui está um exemplo otimizado da implementação do <strong>Fixed-Sized Buffer Pattern</strong> em C:</p>



<p class="wp-block-paragraph">Abaixo está um diagrama em blocos que exemplifica o uso do padrão <strong>Fixed-Sized Buffer Pattern</strong>, veja  código a seguir que representa de forma mais realista o padrão de projeto estudado.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="3408" height="1804" src="https://mcu.tec.br/wp-content/uploads/2025/02/image.png" alt="" class="wp-image-96" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/image.png 3408w, https://mcu.tec.br/wp-content/uploads/2025/02/image-300x159.png 300w" sizes="(max-width: 3408px) 100vw, 3408px" /></figure>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#2e3440ff"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="#include &lt;stdint.h&gt;
// Tipos de dados padronizados
#include &lt;stdbool.h&gt; 
// Booleanos

#define SMALL_BLOCK_SIZE  64
#define MEDIUM_BLOCK_SIZE 128
#define LARGE_BLOCK_SIZE  256
#define BLOCKS_PER_POOL  10  // Número de blocos fixos por pilha
typedef enum { SMALL, MEDIUM, LARGE } BlockSize;

// Estrutura do bloco reutilizável
typedef struct Block {
    struct Block* next;
} Block;

// Estrutura da pilha de blocos

typedef struct {
    Block* free_list;
    uint8_t memory_pool[BLOCKS_PER_POOL][LARGE_BLOCK_SIZE]; // Buffer estático máximo
    uint8_t block_size;
} BlockStack;

// Estrutura do gerenciador de pilhas
typedef struct {
    BlockStack small_stack;
    BlockStack medium_stack;
    BlockStack large_stack;
} StackManager;
// Estrutura da fábrica de objetos
typedef struct {
    StackManager* stack_manager;
} ObjectFactory;

// Inicializa uma pilha de blocos (pré-alocação)
void init_stack(BlockStack* stack, uint8_t block_size) {
    stack-&gt;block_size = block_size;
    stack-&gt;free_list = NULL;
    // Divide o buffer estático em blocos reutilizáveis
    for (int i = 0; i &lt; BLOCKS_PER_POOL; i++) {
        Block* block = (Block*)&amp;stack-&gt;memory_pool[i][0];
        block-&gt;next = stack-&gt;free_list;
        stack-&gt;free_list = block;
    }
}

// Aloca um bloco reutilizando a lista livre
void* allocate_block(BlockStack* stack) {
    if (!stack-&gt;free_list) {
        return NULL; // Nenhum bloco disponível
    }
    Block* block = stack-&gt;free_list;
    stack-&gt;free_list = block-&gt;next;
    return block;&lt;br&gt;}

// Libera um bloco de volta para a pilha
void free_block(BlockStack* stack, void* block) {
    if (!block) return;
    ((Block*)block)-&gt;next = stack-&gt;free_list;
    stack-&gt;free_list = (Block*)block;
}

// Inicializa o gerenciador de pilhas
void init_stack_manager(StackManager* manager) {
    init_stack(&amp;manager-&gt;small_stack, SMALL_BLOCK_SIZE);
    init_stack(&amp;manager-&gt;medium_stack, MEDIUM_BLOCK_SIZE);
    init_stack(&amp;manager-&gt;large_stack, LARGE_BLOCK_SIZE);
}

// Aloca um bloco baseado no tamanho especificado
void* allocate_from_manager(StackManager* manager, BlockSize size) {
    switch (size) {
      case SMALL: 
           return allocate_block(&amp;manager-&gt;small_stack);
      case MEDIUM: 
           return allocate_block(&amp;manager-&gt;medium_stack);
       case LARGE: 
           return allocate_block(&amp;manager-&gt;large_stack)
    }
    return NULL;
}
// Libera um bloco baseado no tamanho especificado

void free_to_manager(StackManager* manager, void* block, BlockSize size) {
    switch (size) {
        case SMALL: free_block(&amp;manager-&gt;small_stack, block); break;
        case MEDIUM: free_block(&amp;manager-&gt;medium_stack, block); break;
        case LARGE: free_block(&amp;manager-&gt;large_stack, block); break;
   }
}

// Inicializa a fábrica de objetos
void init_object_factory(ObjectFactory* factory, StackManager* manager) {
    factory-&gt;stack_manager = manager;&lt;br&gt;}&lt;br&gt;&lt;br&gt;// Cria um objeto utilizando a fábrica&lt;br&gt;void* create_object(ObjectFactory* factory, BlockSize size) {&lt;br&gt;    return allocate_from_manager(factory-&gt;stack_manager, size);&lt;br&gt;}&lt;br&gt;&lt;br&gt;// Libera um objeto utilizando a fábrica&lt;br&gt;void destroy_object(ObjectFactory* factory, void* object, BlockSize size) {
    free_to_manager(factory-&gt;stack_manager, object, size);
}

// Função de exemplo para testar no microcontrolador
void test_memory_allocation() {
    StackManager manager;
    ObjectFactory factory;
    init_stack_manager(&amp;manager);
    init_object_factory(&amp;factory, &amp;manager);
    
    void* obj1 = create_object(&amp;factory, SMALL);
    void* obj2 = create_object(&amp;factory, MEDIUM);
    void* obj3 = create_object(&amp;factory, LARGE);
    
    if (obj1 &amp;&amp; obj2 &amp;&amp; obj3) {
        // Simula LED aceso para indicar sucesso
        // gpio_set_level(LED_GPIO, 1);
    }
    
    destroy_object(&amp;factory, obj1, SMALL);
    destroy_object(&amp;factory, obj2, MEDIUM);
    destroy_object(&amp;factory, obj3, LARGE);
    
    // Simula LED apagado para indicar memória liberada&lt;br&gt;   
    // gpio_set_level(LED_GPIO, 0);&lt;br&gt;
}" style="color:#d8dee9ff;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki nord" style="background-color: #2e3440ff" tabindex="0"><code><span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdint.h</span><span style="color: #ECEFF4">&gt;</span></span>
<span class="line"><span style="color: #616E88">// Tipos de dados padronizados</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">include</span><span style="color: #8FBCBB"> </span><span style="color: #ECEFF4">&lt;</span><span style="color: #8FBCBB">stdbool.h</span><span style="color: #ECEFF4">&gt;</span><span style="color: #8FBCBB"> </span></span>
<span class="line"><span style="color: #616E88">// Booleanos</span></span>
<span class="line"></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">SMALL_BLOCK_SIZE</span><span style="color: #5E81AC">  </span><span style="color: #B48EAD">64</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">MEDIUM_BLOCK_SIZE</span><span style="color: #5E81AC"> </span><span style="color: #B48EAD">128</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">LARGE_BLOCK_SIZE</span><span style="color: #5E81AC">  </span><span style="color: #B48EAD">256</span></span>
<span class="line"><span style="color: #5E81AC; font-weight: bold">#</span><span style="color: #81A1C1">define</span><span style="color: #5E81AC"> </span><span style="color: #88C0D0">BLOCKS_PER_POOL</span><span style="color: #5E81AC">  </span><span style="color: #B48EAD">10</span><span style="color: #616E88">  // Número de blocos fixos por pilha</span></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #5E81AC"> </span><span style="color: #81A1C1">enum</span><span style="color: #5E81AC"> </span><span style="color: #ECEFF4">{</span><span style="color: #5E81AC"> SMALL</span><span style="color: #ECEFF4">,</span><span style="color: #5E81AC"> MEDIUM</span><span style="color: #ECEFF4">,</span><span style="color: #5E81AC"> LARGE </span><span style="color: #ECEFF4">}</span><span style="color: #5E81AC"> BlockSize</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Estrutura do bloco reutilizável</span></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> Block </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> Block</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> next</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> Block</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Estrutura da pilha de blocos</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    Block</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> free_list</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">uint8_t</span><span style="color: #D8DEE9FF"> memory_pool</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">BLOCKS_PER_POOL</span><span style="color: #ECEFF4">][</span><span style="color: #D8DEE9FF">LARGE_BLOCK_SIZE</span><span style="color: #ECEFF4">]</span><span style="color: #81A1C1">;</span><span style="color: #616E88"> // Buffer estático máximo</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">uint8_t</span><span style="color: #D8DEE9FF"> block_size</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> BlockStack</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Estrutura do gerenciador de pilhas</span></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    BlockStack small_stack</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    BlockStack medium_stack</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    BlockStack large_stack</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> StackManager</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #616E88">// Estrutura da fábrica de objetos</span></span>
<span class="line"><span style="color: #81A1C1">typedef</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">struct</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    StackManager</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> stack_manager</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span><span style="color: #D8DEE9FF"> ObjectFactory</span><span style="color: #81A1C1">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Inicializa uma pilha de blocos (pré-alocação)</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">init_stack</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">BlockStack</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">uint8_t</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">block_size</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">block_size</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> block_size</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">NULL;</span></span>
<span class="line"><span style="color: #ECEFF4">    </span><span style="color: #616E88">// Divide o buffer estático em blocos reutilizáveis</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">for</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">int</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #B48EAD">0</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i </span><span style="color: #81A1C1">&lt;</span><span style="color: #D8DEE9FF"> BLOCKS_PER_POOL</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> i</span><span style="color: #81A1C1">++</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        Block</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> block </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">Block</span><span style="color: #81A1C1">*</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">memory_pool</span><span style="color: #ECEFF4">[</span><span style="color: #D8DEE9FF">i</span><span style="color: #ECEFF4">][</span><span style="color: #B48EAD">0</span><span style="color: #ECEFF4">]</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">block</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">next</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> block</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Aloca um bloco reutilizando a lista livre</span></span>
<span class="line"><span style="color: #81A1C1">void*</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocate_block</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">BlockStack</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">stack</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">!</span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">NULL;</span><span style="color: #616E88"> // Nenhum bloco disponível</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #D8DEE9FF">    Block</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> block </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">block</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">next</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> block</span><span style="color: #81A1C1">;&lt;</span><span style="color: #D8DEE9FF">br</span><span style="color: #81A1C1">&gt;</span><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Libera um bloco de volta para a pilha</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">free_block</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">BlockStack</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">void*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">block</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">!</span><span style="color: #D8DEE9FF">block</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">return;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">((</span><span style="color: #D8DEE9FF">Block</span><span style="color: #81A1C1">*</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF">block</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">next</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #D8DEE9">stack</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">free_list</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">Block</span><span style="color: #81A1C1">*</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF">block</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Inicializa o gerenciador de pilhas</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">init_stack_manager</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">StackManager</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">manager</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">init_stack</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">small_stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> SMALL_BLOCK_SIZE</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">init_stack</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">medium_stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> MEDIUM_BLOCK_SIZE</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">init_stack</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">large_stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> LARGE_BLOCK_SIZE</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Aloca um bloco baseado no tamanho especificado</span></span>
<span class="line"><span style="color: #81A1C1">void*</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocate_from_manager</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">StackManager</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">manager</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> BlockSize </span><span style="color: #D8DEE9">size</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">switch</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">size</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">      </span><span style="color: #81A1C1">case</span><span style="color: #D8DEE9FF"> SMALL</span><span style="color: #ECEFF4">:</span><span style="color: #D8DEE9FF"> </span></span>
<span class="line"><span style="color: #D8DEE9FF">           </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocate_block</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">small_stack</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">      </span><span style="color: #81A1C1">case</span><span style="color: #D8DEE9FF"> MEDIUM</span><span style="color: #ECEFF4">:</span><span style="color: #D8DEE9FF"> </span></span>
<span class="line"><span style="color: #D8DEE9FF">           </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocate_block</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">medium_stack</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">       </span><span style="color: #81A1C1">case</span><span style="color: #D8DEE9FF"> LARGE</span><span style="color: #ECEFF4">:</span><span style="color: #D8DEE9FF"> </span></span>
<span class="line"><span style="color: #D8DEE9FF">           </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">allocate_block</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">large_stack</span><span style="color: #ECEFF4">)</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">return</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">NULL;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #616E88">// Libera um bloco baseado no tamanho especificado</span></span>
<span class="line"></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">free_to_manager</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">StackManager</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">manager</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">void*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">block</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> BlockSize </span><span style="color: #D8DEE9">size</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">switch</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">size</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #81A1C1">case</span><span style="color: #D8DEE9FF"> SMALL</span><span style="color: #ECEFF4">:</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">free_block</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">small_stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> block</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">break;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #81A1C1">case</span><span style="color: #D8DEE9FF"> MEDIUM</span><span style="color: #ECEFF4">:</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">free_block</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">medium_stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> block</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">break;</span></span>
<span class="line"><span style="color: #D8DEE9FF">        </span><span style="color: #81A1C1">case</span><span style="color: #D8DEE9FF"> LARGE</span><span style="color: #ECEFF4">:</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">free_block</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">large_stack</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> block</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">break;</span></span>
<span class="line"><span style="color: #D8DEE9FF">   </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Inicializa a fábrica de objetos</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">init_object_factory</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">ObjectFactory</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> StackManager</span><span style="color: #81A1C1">*</span><span style="color: #D8DEE9FF"> </span><span style="color: #D8DEE9">manager</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #D8DEE9">factory</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">stack_manager</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> manager</span><span style="color: #81A1C1">;&lt;</span><span style="color: #D8DEE9FF">br</span><span style="color: #81A1C1">&gt;</span><span style="color: #ECEFF4">}</span><span style="color: #81A1C1">&lt;</span><span style="color: #D8DEE9FF">br</span><span style="color: #81A1C1">&gt;&lt;</span><span style="color: #D8DEE9FF">br</span><span style="color: #81A1C1">&gt;</span><span style="color: #616E88">// Cria um objeto utilizando a fábrica&lt;br&gt;void* create_object(ObjectFactory* factory, BlockSize size) {&lt;br&gt;    return allocate_from_manager(factory-&gt;stack_manager, size);&lt;br&gt;}&lt;br&gt;&lt;br&gt;// Libera um objeto utilizando a fábrica&lt;br&gt;void destroy_object(ObjectFactory* factory, void* object, BlockSize size) {</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">free_to_manager</span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">factory</span><span style="color: #81A1C1">-&gt;</span><span style="color: #D8DEE9">stack_manager</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> object</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> size</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #616E88">// Função de exemplo para testar no microcontrolador</span></span>
<span class="line"><span style="color: #81A1C1">void</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">test_memory_allocation</span><span style="color: #ECEFF4">()</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #D8DEE9FF">    StackManager manager</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    ObjectFactory factory</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">init_stack_manager</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">init_object_factory</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> </span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">manager</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">void*</span><span style="color: #D8DEE9FF"> obj1 </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">create_object</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> SMALL</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">void*</span><span style="color: #D8DEE9FF"> obj2 </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">create_object</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> MEDIUM</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">void*</span><span style="color: #D8DEE9FF"> obj3 </span><span style="color: #81A1C1">=</span><span style="color: #D8DEE9FF"> </span><span style="color: #88C0D0">create_object</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> LARGE</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #81A1C1">if</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">(</span><span style="color: #D8DEE9FF">obj1 </span><span style="color: #81A1C1">&amp;&amp;</span><span style="color: #D8DEE9FF"> obj2 </span><span style="color: #81A1C1">&amp;&amp;</span><span style="color: #D8DEE9FF"> obj3</span><span style="color: #ECEFF4">)</span><span style="color: #D8DEE9FF"> </span><span style="color: #ECEFF4">{</span></span>
<span class="line"><span style="color: #ECEFF4">        </span><span style="color: #616E88">// Simula LED aceso para indicar sucesso</span></span>
<span class="line"><span style="color: #ECEFF4">        </span><span style="color: #616E88">// gpio_set_level(LED_GPIO, 1);</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #ECEFF4">}</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">destroy_object</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> obj1</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> SMALL</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">destroy_object</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> obj2</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> MEDIUM</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span><span style="color: #88C0D0">destroy_object</span><span style="color: #ECEFF4">(</span><span style="color: #81A1C1">&amp;</span><span style="color: #D8DEE9FF">factory</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> obj3</span><span style="color: #ECEFF4">,</span><span style="color: #D8DEE9FF"> LARGE</span><span style="color: #ECEFF4">)</span><span style="color: #81A1C1">;</span></span>
<span class="line"><span style="color: #D8DEE9FF">    </span></span>
<span class="line"><span style="color: #ECEFF4">    </span><span style="color: #616E88">// Simula LED apagado para indicar memória liberada&lt;br&gt;   </span></span>
<span class="line"><span style="color: #ECEFF4">    </span><span style="color: #616E88">// gpio_set_level(LED_GPIO, 0);&lt;br&gt;</span></span>
<span class="line"><span style="color: #ECEFF4">}</span></span></code></pre></div>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h1 class="wp-block-heading">Material de apoio no GitHub</h1>



<ul class="wp-block-list">
<li><a href="https://github.com/ArvoreDosSaberes/Design-Patterns">https://github.com/ArvoreDosSaberes/Design-Patterns</a></li>
</ul>



<p class="wp-block-paragraph"></p><p>The post <a href="https://mcu.tec.br/padroes-de-projetos/fixed-sized-buffer-pattern/">Fixed-Sized Buffer Pattern</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">95</post-id>	</item>
		<item>
		<title>Padrões de Projeto para Sistemas Embarcados em C</title>
		<link>https://mcu.tec.br/linguagem/c/padroes-de-projeto-para-sistemas-embarcados-em-c/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=padroes-de-projeto-para-sistemas-embarcados-em-c</link>
		
		<dc:creator><![CDATA[Carlos Delfino]]></dc:creator>
		<pubDate>Fri, 21 Feb 2025 03:28:16 +0000</pubDate>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Padrões de Projetos]]></category>
		<category><![CDATA[arquitetura de software embarcado]]></category>
		<category><![CDATA[Broker Pattern]]></category>
		<category><![CDATA[Component-Based Architecture Pattern]]></category>
		<category><![CDATA[concorrência em sistemas embarcados]]></category>
		<category><![CDATA[Critical Section Pattern]]></category>
		<category><![CDATA[Cyclic Executive Pattern]]></category>
		<category><![CDATA[Data Bus Pattern]]></category>
		<category><![CDATA[desenvolvimento embarcado]]></category>
		<category><![CDATA[design patterns C]]></category>
		<category><![CDATA[Dynamic Priority Pattern]]></category>
		<category><![CDATA[Fixed-Sized Buffer Pattern]]></category>
		<category><![CDATA[Garbage Collection Pattern]]></category>
		<category><![CDATA[Garbage Compactor Pattern]]></category>
		<category><![CDATA[gerenciamento de memória]]></category>
		<category><![CDATA[Guarded Call Pattern]]></category>
		<category><![CDATA[Heterogeneous Redundancy Pattern]]></category>
		<category><![CDATA[Hierarchical Control Pattern]]></category>
		<category><![CDATA[Highest Locker Pattern]]></category>
		<category><![CDATA[Homogeneous Redundancy Pattern]]></category>
		<category><![CDATA[Interrupt Pattern]]></category>
		<category><![CDATA[Layered Pattern]]></category>
		<category><![CDATA[Message Queuing Pattern]]></category>
		<category><![CDATA[microcontroladores]]></category>
		<category><![CDATA[Microkernel Architecture Pattern]]></category>
		<category><![CDATA[Monitor-Actuator Pattern]]></category>
		<category><![CDATA[Observer Pattern]]></category>
		<category><![CDATA[Ordered Locking Pattern]]></category>
		<category><![CDATA[otimização de firmware]]></category>
		<category><![CDATA[padrões de projeto]]></category>
		<category><![CDATA[Pool Allocation Pattern]]></category>
		<category><![CDATA[Priority Ceiling Pattern]]></category>
		<category><![CDATA[Priority Inheritance Pattern]]></category>
		<category><![CDATA[programação em C]]></category>
		<category><![CDATA[Protected Single Channel Pattern]]></category>
		<category><![CDATA[Proxy Pattern]]></category>
		<category><![CDATA[Recursive Containment Pattern]]></category>
		<category><![CDATA[Remote Method Call Pattern]]></category>
		<category><![CDATA[Rendezvous Pattern]]></category>
		<category><![CDATA[ROOM Pattern]]></category>
		<category><![CDATA[Round Robin Pattern]]></category>
		<category><![CDATA[rtos]]></category>
		<category><![CDATA[Safety Executive Pattern.]]></category>
		<category><![CDATA[Sanity Check Pattern]]></category>
		<category><![CDATA[Shared Memory Pattern]]></category>
		<category><![CDATA[Simultaneous Locking Pattern]]></category>
		<category><![CDATA[sistemas embarcados]]></category>
		<category><![CDATA[Smart Pointer Pattern]]></category>
		<category><![CDATA[software embarcado]]></category>
		<category><![CDATA[Static Allocation Pattern]]></category>
		<category><![CDATA[Static Priority Pattern]]></category>
		<category><![CDATA[Triple Modular Redundancy (TMR) Pattern]]></category>
		<category><![CDATA[Virtual Machine Pattern]]></category>
		<category><![CDATA[Watchdog Pattern]]></category>
		<guid isPermaLink="false">https://mcu.tec.br/?p=69</guid>

					<description><![CDATA[<p>Descubra os principais padrões de projeto para sistemas embarcados em C e como aplicá-los para melhorar modularidade, concorrência, gerenciamento de memória e confiabilidade.</p>
<p>The post <a href="https://mcu.tec.br/linguagem/c/padroes-de-projeto-para-sistemas-embarcados-em-c/">Padrões de Projeto para Sistemas Embarcados em C</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph">Os padrões de projeto são soluções reutilizáveis para problemas recorrentes no desenvolvimento de software. Em sistemas embarcados, onde recursos como memória e processamento são limitados, escolher a estrutura correta pode ser decisivo para o sucesso do projeto.</p>



<p class="wp-block-paragraph">Neste artigo, iniciamos uma série de artigos sobre padrões de projeto aplicáveis ao desenvolvimento em C para microcontroladores. Para cada padrão, descreveremos seu propósito, vantagens e um cenário de aplicação. Cada um desses padrões será tratado com mais profundidade em artigos separados ao longo desta série.</p>



<p class="wp-block-paragraph">Este material tem como base os seguintes livros de referência:</p>



<ul class="wp-block-list">
<li><em>Design Patterns for Embedded Systems in C</em> de Bruce Powel Douglass</li>



<li><em>Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems</em> de Bruce Powel Douglass</li>



<li><em>Patterns of Enterprise Application Architecture</em> de Martin Fowler</li>



<li><em>Domain-Driven Design</em> de Eric Evans</li>



<li><em>Design Patterns: Elements of Reusable Object-Oriented Software</em> de Erich Gamma, Richard Helm, Ralph Johnson e John Vlissides (Gang of Four)</li>
</ul>



<figure class="wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="700" height="862" data-id="72" src="https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-for-Embedded-Systems-in-C-Bruce-Powel-Douglass.jpg" alt="Design Patterns for Embedded Systems in C.
An Embedded Software Engineering Toolkit
Bruce Powel Douglass
" class="wp-image-72" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-for-Embedded-Systems-in-C-Bruce-Powel-Douglass.jpg 700w, https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-for-Embedded-Systems-in-C-Bruce-Powel-Douglass-244x300.jpg 244w" sizes="(max-width: 700px) 100vw, 700px" /></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="408" height="500" data-id="73" src="https://mcu.tec.br/wp-content/uploads/2025/02/Real-Time-Design-Patterns_-Robust-Scalable-Architecture-for-Real-Time-Systems-by-Douglass-Bruce-Powel-Paperback-Bruce-Powel-Douglass.jpg" alt="Real-Time Design Patterns
Robust Scalable Architecture for Real-Time Systems
Bruce Powelo Douglass" class="wp-image-73" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/Real-Time-Design-Patterns_-Robust-Scalable-Architecture-for-Real-Time-Systems-by-Douglass-Bruce-Powel-Paperback-Bruce-Powel-Douglass.jpg 408w, https://mcu.tec.br/wp-content/uploads/2025/02/Real-Time-Design-Patterns_-Robust-Scalable-Architecture-for-Real-Time-Systems-by-Douglass-Bruce-Powel-Paperback-Bruce-Powel-Douglass-245x300.jpg 245w" sizes="(max-width: 408px) 100vw, 408px" /></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="791" height="1024" data-id="79" src="https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-Erich-Gama-Richard-Helm-Ralph-Johnson-John-Vlissides-791x1024.jpg" alt="Design Patterns
Elements of Reusable Object-Oriented Software
Gangue dos quadro" class="wp-image-79" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-Erich-Gama-Richard-Helm-Ralph-Johnson-John-Vlissides-791x1024.jpg 791w, https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-Erich-Gama-Richard-Helm-Ralph-Johnson-John-Vlissides-232x300.jpg 232w, https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-Erich-Gama-Richard-Helm-Ralph-Johnson-John-Vlissides-768x994.jpg 768w, https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-Erich-Gama-Richard-Helm-Ralph-Johnson-John-Vlissides-1187x1536.jpg 1187w, https://mcu.tec.br/wp-content/uploads/2025/02/Design-Patterns-Erich-Gama-Richard-Helm-Ralph-Johnson-John-Vlissides.jpg 1275w" sizes="(max-width: 791px) 100vw, 791px" /></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="769" height="1024" data-id="81" src="https://mcu.tec.br/wp-content/uploads/2025/02/Domain-Driven-Design-Tackling-Complexity-in-the-Heart-of-Software-Addison-Wesley-Professional-2003-Eric-Evans-769x1024.jpg" alt="Domain-Driven Design
Tacking Complexity in the Heart of Software
Eric Evans" class="wp-image-81" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/Domain-Driven-Design-Tackling-Complexity-in-the-Heart-of-Software-Addison-Wesley-Professional-2003-Eric-Evans-769x1024.jpg 769w, https://mcu.tec.br/wp-content/uploads/2025/02/Domain-Driven-Design-Tackling-Complexity-in-the-Heart-of-Software-Addison-Wesley-Professional-2003-Eric-Evans-225x300.jpg 225w, https://mcu.tec.br/wp-content/uploads/2025/02/Domain-Driven-Design-Tackling-Complexity-in-the-Heart-of-Software-Addison-Wesley-Professional-2003-Eric-Evans-768x1023.jpg 768w, https://mcu.tec.br/wp-content/uploads/2025/02/Domain-Driven-Design-Tackling-Complexity-in-the-Heart-of-Software-Addison-Wesley-Professional-2003-Eric-Evans-1154x1536.jpg 1154w, https://mcu.tec.br/wp-content/uploads/2025/02/Domain-Driven-Design-Tackling-Complexity-in-the-Heart-of-Software-Addison-Wesley-Professional-2003-Eric-Evans.jpg 1240w" sizes="(max-width: 769px) 100vw, 769px" /></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="525" height="659" data-id="82" src="https://mcu.tec.br/wp-content/uploads/2025/02/Patterns-of-Enterprise-Application-Architecture-Martin-Fowler.jpg" alt="Patterns of Enterprise Application Architecture
Martin Fowler" class="wp-image-82" srcset="https://mcu.tec.br/wp-content/uploads/2025/02/Patterns-of-Enterprise-Application-Architecture-Martin-Fowler.jpg 525w, https://mcu.tec.br/wp-content/uploads/2025/02/Patterns-of-Enterprise-Application-Architecture-Martin-Fowler-239x300.jpg 239w" sizes="(max-width: 525px) 100vw, 525px" /></figure>
</figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Minha Jornada com Padrões de Projeto em C</h2>



<p class="wp-block-paragraph">Quando comecei a programar em Java, há 20 anos, fiquei fascinado com a capacidade da linguagem de representar objetos em forma de código. Isso me levou a buscar mais conhecimento sobre o assunto, e logo me deparei com livros como <em>Domain-Driven Design</em> de Eric Evans, <em>Patterns of Enterprise Application Architecture</em> de Martin Fowler e <em>Design Patterns</em>. O entendimento desses padrões de projeto abriu minha mente para a importância de desenvolver código altamente estruturado e de qualidade.</p>



<p class="wp-block-paragraph">Entretanto, nunca havia considerado que no contexto procedural da linguagem C também pudessem existir tais padrões. Para minha surpresa, em uma conversa recente com meu tutor na Embarcatech, fui apresentado ao conceito de Orientação a Objetos em C. Não estou falando de C++, mas sim de C puro! Isso me despertou uma enorme curiosidade, e iniciei uma pesquisa sobre o tema. Foi então que me deparei com os livros de Bruce Powel Douglass sobre padrões de projeto em sistemas embarcados.</p>



<p class="wp-block-paragraph">Ainda não tive meu <em>boooommmm</em> de entendimento total no contexto de microcontroladores, pois não consegui ler os livros por completo. No entanto, como tudo que estudo vira material para meus sites e livros (um dia eles saem!), decidi abordar um padrão de projeto por mês e compartilhar essas descobertas com vocês.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading"><strong>Padrões de Projeto para Sistemas Embarcados</strong></h2>



<p class="wp-block-paragraph">Aqui está uma lista abrangente dos principais padrões de projeto aplicáveis ao desenvolvimento de software para microcontroladores e sistemas embarcados. Eles estão organizados por categoria para facilitar a compreensão:</p>



<h3 class="wp-block-heading"><strong>1. Padrões de Arquitetura de Subsistema e Componentes</strong></h3>



<p class="wp-block-paragraph">Os padrões desta categoria ajudam a estruturar o software embarcado de forma modular, facilitando a manutenção, a escalabilidade e a reutilização de código. Eles definem como os diferentes módulos do sistema interagem entre si e organizam a arquitetura geral do software.</p>



<h3 class="wp-block-heading"><strong>1.1 Layered Pattern (Padrão em Camadas)</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Mistura de responsabilidades dentro do código, dificultando a manutenção e a reutilização.</li>



<li><strong>Cenário de uso</strong>: Projetos que exigem separação clara entre hardware, drivers, middleware e aplicação.</li>



<li><strong>Vantagens</strong>: Organização do código, maior reutilização de componentes e facilidade de manutenção.</li>



<li><strong>O que é</strong>: Divide o sistema em camadas hierárquicas onde cada uma depende apenas da camada inferior, promovendo um código mais organizado e de fácil escalabilidade.</li>
</ul>



<h3 class="wp-block-heading"><strong>1.2 Microkernel Architecture Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Sistemas grandes e complexos com funcionalidades variáveis que precisam ser ativadas ou desativadas dinamicamente.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados modulares que precisam suportar diferentes configurações de hardware ou software.</li>



<li><strong>Vantagens</strong>: Melhor gerenciamento de recursos e flexibilidade na ativação/desativação de módulos.</li>



<li><strong>O que é</strong>: Mantém um núcleo mínimo do sistema (microkernel) e permite adicionar funcionalidades por meio de módulos externos.</li>
</ul>



<h3 class="wp-block-heading"><strong>1.3 Component-Based Architecture Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Alto acoplamento entre módulos, dificultando a reutilização e a substituição de componentes.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que precisam de alta modularidade, como IoT e automação industrial.</li>



<li><strong>Vantagens</strong>: Facilita a manutenção e a atualização do sistema sem afetar outros componentes.</li>



<li><strong>O que é</strong>: Estrutura o software em componentes independentes que interagem por meio de interfaces bem definidas.</li>
</ul>



<h3 class="wp-block-heading"><strong>1.4 Virtual Machine Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Dificuldade em portar software para diferentes plataformas de hardware.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que precisam rodar em múltiplos tipos de hardware sem grandes adaptações no código.</li>



<li><strong>Vantagens</strong>: Independência de hardware e reutilização de código entre diferentes plataformas.</li>



<li><strong>O que é</strong>: Cria uma camada de abstração que simula um ambiente de execução padronizado, permitindo que o software funcione de forma mais genérica.</li>
</ul>



<h3 class="wp-block-heading"><strong>1.5 Hierarchical Control Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falta de organização em sistemas embarcados que possuem múltiplos níveis de controle.</li>



<li><strong>Cenário de uso</strong>: Sistemas que exigem tomada de decisão em diferentes níveis, como controle de motores e automação.</li>



<li><strong>Vantagens</strong>: Melhor separação de responsabilidades e hierarquia clara no fluxo de controle.</li>



<li><strong>O que é</strong>: Divide o controle do sistema em diferentes níveis hierárquicos, permitindo um gerenciamento mais eficiente e modular.</li>
</ul>



<h3 class="wp-block-heading"><strong>1.6 Recursive Containment Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Complexidade na organização de subsistemas que possuem componentes recursivos ou aninhados.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que possuem módulos que precisam ser tratados como subsistemas independentes.</li>



<li><strong>Vantagens</strong>: Organização modular clara e facilidade na expansão do sistema.</li>



<li><strong>O que é</strong>: Estrutura os componentes do sistema de maneira hierárquica e recursiva, onde cada elemento pode conter outros elementos semelhantes.</li>
</ul>



<h3 class="wp-block-heading"><strong>1.7 ROOM Pattern (Real-Time Object-Oriented Modeling)</strong></h3>



<p class="wp-block-paragraph"><strong>O que é</strong>: Um padrão que fornece uma abordagem orientada a objetos para modelagem de sistemas de tempo real.</p>



<p class="wp-block-paragraph"><strong>Problema que resolve</strong>: Falta de um modelo estruturado para desenvolvimento orientado a objetos em sistemas embarcados.</p>



<p class="wp-block-paragraph"><strong>Cenário de uso</strong>: Sistemas de tempo real que precisam seguir um modelo de desenvolvimento baseado em objetos.</p>



<p class="wp-block-paragraph"><strong>Vantagens</strong>: Modelagem bem definida, facilitando o desenvolvimento e manutenção do sistema.</p>



<h2 class="wp-block-heading"><strong>2. Padrões de Concorrência</strong></h2>



<p class="wp-block-paragraph">Os padrões desta categoria lidam com a execução de múltiplas tarefas em sistemas embarcados, garantindo que processos concorrentes operem de maneira eficiente e segura. Eles ajudam a evitar condições de corrida, otimizar a comunicação entre tarefas e melhorar a previsibilidade do sistema.</p>



<h3 class="wp-block-heading"><strong>2.1 Message Queuing Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Concorrência e sincronização inadequada entre diferentes tarefas que compartilham dados.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados multitarefa onde tarefas precisam trocar informações de forma controlada.</li>



<li><strong>Vantagens</strong>: Evita condições de corrida e melhora a organização da comunicação entre tarefas.</li>



<li><strong>O que é</strong>: Utiliza filas de mensagens para permitir a comunicação assíncrona entre tarefas de forma controlada.</li>
</ul>



<h3 class="wp-block-heading"><strong>2.2 Interrupt Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Latência alta ao lidar com eventos externos devido a verificações contínuas (polling).</li>



<li><strong>Cenário de uso</strong>: Sistemas que precisam responder rapidamente a eventos externos, como acionamento de sensores.</li>



<li><strong>Vantagens</strong>: Reduz consumo de CPU, melhora tempo de resposta e eficiência energética.</li>



<li><strong>O que é</strong>: Utiliza interrupções de hardware para lidar com eventos externos de forma imediata, evitando verificações constantes.</li>
</ul>



<h3 class="wp-block-heading"><strong>2.3 Guarded Call Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Concorrência inadequada e acesso simultâneo a recursos compartilhados.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados multitarefa que precisam garantir a execução segura de chamadas a funções compartilhadas.</li>



<li><strong>Vantagens</strong>: Previne corrupção de dados e melhora a confiabilidade do sistema.</li>



<li><strong>O que é</strong>: Implementa verificações e sincronização para garantir que chamadas a funções críticas sejam executadas apenas quando seguras.</li>
</ul>



<h3 class="wp-block-heading"><strong>2.4 Rendezvous Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Sincronização inadequada entre duas ou mais tarefas que precisam se comunicar diretamente.</li>



<li><strong>Cenário de uso</strong>: Sistemas onde duas tarefas dependem do estado da outra para avançar, como protocolos de comunicação.</li>



<li><strong>Vantagens</strong>: Melhora a coordenação entre tarefas e evita espera passiva.</li>



<li><strong>O que é</strong>: Estabelece um mecanismo onde duas tarefas precisam estar prontas simultaneamente para prosseguir com a comunicação.</li>
</ul>



<h3 class="wp-block-heading"><strong>2.5 Cyclic Executive Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Complexidade e overhead na gestão de múltiplas tarefas concorrentes.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados simples sem RTOS, onde tarefas precisam ser executadas periodicamente.</li>



<li><strong>Vantagens</strong>: Controle determinístico e fácil implementação.</li>



<li><strong>O que é</strong>: Um loop fixo que executa cada tarefa em uma ordem predefinida dentro de um ciclo fixo de tempo.</li>
</ul>



<h3 class="wp-block-heading"><strong>2.6 Round Robin Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falta de tempo de CPU equitativo entre tarefas concorrentes.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados com multitarefa onde cada processo deve receber um tempo justo de execução.</li>



<li><strong>Vantagens</strong>: Distribuição justa de CPU entre tarefas, evitando monopolização do processador.</li>



<li><strong>O que é</strong>: Um mecanismo de escalonamento que alterna a execução de cada tarefa por um tempo determinado, em um ciclo contínuo.</li>
</ul>



<h3 class="wp-block-heading"><strong>2.7 Static Priority Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falta de controle sobre a execução de tarefas críticas em tempo real.</li>



<li><strong>Cenário de uso</strong>: Sistemas de tempo real que exigem resposta imediata para determinadas tarefas prioritárias.</li>



<li><strong>Vantagens</strong>: Garante que tarefas críticas sejam executadas antes das menos prioritárias.</li>



<li><strong>O que é</strong>: Define prioridades fixas para cada tarefa, garantindo que aquelas com maior prioridade sempre sejam executadas primeiro.</li>
</ul>



<h3 class="wp-block-heading"><strong>2.8 Dynamic Priority Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Problemas de bloqueios ou inversão de prioridade em sistemas multitarefa.</li>



<li><strong>Cenário de uso</strong>: Sistemas onde a prioridade das tarefas pode mudar com base na carga de trabalho.</li>



<li><strong>Vantagens</strong>: Melhora o balanceamento de carga do processador e evita deadlocks.</li>



<li><strong>O que é</strong>: Ajusta dinamicamente as prioridades das tarefas conforme necessário para garantir melhor desempenho e tempo de resposta.</li>
</ul>



<h2 class="wp-block-heading"><strong>3. Padrões de Gerenciamento de Memória</strong></h2>



<p class="wp-block-paragraph">Os padrões desta categoria ajudam a otimizar o uso da memória em sistemas embarcados, onde os recursos são frequentemente limitados. Eles garantem que a alocação e a liberação de memória ocorram de forma eficiente, evitando desperdícios e garantindo previsibilidade no consumo de RAM.</p>



<h3 class="wp-block-heading"><strong>3.1 Static Allocation Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Uso imprevisível de memória devido a alocações dinâmicas, que podem causar fragmentação e falhas em sistemas embarcados críticos.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados com recursos limitados que precisam de controle total sobre a alocação de memória.</li>



<li><strong>Vantagens</strong>: Evita fragmentação da memória e melhora a previsibilidade do uso de RAM.</li>



<li><strong>O que é</strong>: Utiliza apenas alocações estáticas, definindo variáveis globais e buffers fixos durante a compilação.</li>
</ul>



<h3 class="wp-block-heading"><strong>3.2 Pool Allocation Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Ineficiência e fragmentação de memória ao alocar e desalocar pequenos blocos dinamicamente.</li>



<li><strong>Cenário de uso</strong>: Sistemas que precisam gerenciar dinamicamente a alocação de pequenos blocos de memória sem risco de fragmentação.</li>



<li><strong>Vantagens</strong>: Reduz fragmentação e melhora a previsibilidade no tempo de acesso à memória.</li>



<li><strong>O que é</strong>: Aloca um conjunto fixo de blocos de memória e os gerencia em um pool pré-definido, evitando alocações e desalocações imprevisíveis.</li>
</ul>



<h3 class="wp-block-heading"><strong>3.3 Fixed-Sized Buffer Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Overhead e fragmentação ao lidar com buffers de tamanho variável.</li>



<li><strong>Cenário de uso</strong>: Aplicações que precisam de buffers para comunicação ou armazenamento temporário de dados.</li>



<li><strong>Vantagens</strong>: Maior eficiência no gerenciamento de memória e redução de falhas associadas a alocações dinâmicas.</li>



<li><strong>O que é</strong>: Define buffers de tamanho fixo e pré-alocados para operações específicas, garantindo previsibilidade e eficiência no uso da memória.</li>
</ul>



<h3 class="wp-block-heading"><strong>3.4 Smart Pointer Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Vazamento de memória devido a alocações dinâmicas sem liberação adequada.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que precisam gerenciar dinamicamente a memória sem risco de vazamentos.</li>



<li><strong>Vantagens</strong>: Reduz a necessidade de gerenciar manualmente a liberação de memória, evitando erros de alocação.</li>



<li><strong>O que é</strong>: Implementa ponteiros inteligentes que controlam automaticamente a alocação e liberação da memória associada.</li>
</ul>



<h3 class="wp-block-heading"><strong>3.5 Garbage Collection Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Necessidade de liberação manual de memória em sistemas que fazem uso intenso de alocação dinâmica.</li>



<li><strong>Cenário de uso</strong>: Aplicações complexas que utilizam alocação dinâmica e exigem gerenciamento automatizado da memória.</li>



<li><strong>Vantagens</strong>: Libera automaticamente memória não utilizada, reduzindo erros de alocação e melhorando a estabilidade do sistema.</li>



<li><strong>O que é</strong>: Implementa um mecanismo que monitora e libera memória não referenciada automaticamente.</li>
</ul>



<h3 class="wp-block-heading"><strong>3.6 Garbage Compactor Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Fragmentação de memória ao longo do tempo devido a alocações e desalocações dinâmicas.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados com uso dinâmico de memória onde a fragmentação pode comprometer a alocação de novos blocos.</li>



<li><strong>Vantagens</strong>: Reduz fragmentação de memória e melhora a eficiência da alocação.</li>



<li><strong>O que é</strong>: Reorganiza a memória alocada periodicamente para eliminar fragmentação e garantir blocos contíguos livres.</li>
</ul>



<h2 class="wp-block-heading"><strong>4. Padrões de Gerenciamento de Recursos</strong></h2>



<p class="wp-block-paragraph">Os padrões desta categoria garantem o acesso eficiente e seguro a recursos compartilhados em sistemas embarcados. Eles ajudam a evitar problemas como deadlocks, inversão de prioridade e acesso concorrente inadequado a periféricos e variáveis globais.</p>



<h3 class="wp-block-heading"><strong>4.1 Critical Section Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Condições de corrida causadas por múltiplas tarefas acessando simultaneamente um mesmo recurso.</li>



<li><strong>Cenário de uso</strong>: Sistemas multitarefa onde variáveis globais ou periféricos precisam ser acessados por diferentes processos.</li>



<li><strong>Vantagens</strong>: Evita corrupção de dados e garante acesso controlado aos recursos compartilhados.</li>



<li><strong>O que é</strong>: Implementa seções críticas onde apenas uma tarefa pode acessar um recurso por vez, utilizando mutexes, semáforos ou desativação de interrupções.</li>
</ul>



<h3 class="wp-block-heading"><strong>4.2 Priority Inheritance Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Inversão de prioridade, onde uma tarefa de baixa prioridade impede a execução de uma tarefa crítica.</li>



<li><strong>Cenário de uso</strong>: Sistemas de tempo real onde tarefas críticas podem ser bloqueadas por tarefas de menor prioridade.</li>



<li><strong>Vantagens</strong>: Garante que tarefas de alta prioridade não fiquem bloqueadas desnecessariamente.</li>



<li><strong>O que é</strong>: Permite que uma tarefa de baixa prioridade herde temporariamente a prioridade de uma tarefa de maior prioridade até liberar o recurso.</li>
</ul>



<h3 class="wp-block-heading"><strong>4.3 Highest Locker Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Deadlocks gerados por múltiplas tarefas bloqueando recursos de forma desordenada.</li>



<li><strong>Cenário de uso</strong>: Sistemas onde várias tarefas competem por múltiplos recursos compartilhados.</li>



<li><strong>Vantagens</strong>: Evita deadlocks e melhora a previsibilidade do sistema.</li>



<li><strong>O que é</strong>: Assegura que apenas a tarefa com a maior prioridade entre as que precisam do recurso possa bloqueá-lo, forçando uma ordem de acesso previsível.</li>
</ul>



<h3 class="wp-block-heading"><strong>4.4 Priority Ceiling Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Inversão de prioridade e bloqueios inesperados devido a compartilhamento inadequado de recursos.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados críticos onde múltiplas tarefas acessam o mesmo recurso.</li>



<li><strong>Vantagens</strong>: Evita bloqueios imprevisíveis e melhora o tempo de resposta das tarefas críticas.</li>



<li><strong>O que é</strong>: Define uma prioridade máxima para cada recurso compartilhado, garantindo que apenas tarefas com prioridade igual ou superior possam acessá-lo.</li>
</ul>



<h3 class="wp-block-heading"><strong>4.5 Simultaneous Locking Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Deadlocks e ineficiência ao acessar múltiplos recursos compartilhados ao mesmo tempo.</li>



<li><strong>Cenário de uso</strong>: Sistemas onde múltiplas tarefas precisam acessar vários recursos simultaneamente.</li>



<li><strong>Vantagens</strong>: Reduz o risco de deadlocks e melhora a eficiência no gerenciamento de recursos.</li>



<li><strong>O que é</strong>: Implementa um mecanismo de bloqueio simultâneo de todos os recursos necessários antes de iniciar uma operação crítica.</li>
</ul>



<h3 class="wp-block-heading"><strong>4.6 Ordered Locking Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Deadlocks causados por ordem inconsistente de bloqueio de recursos.</li>



<li><strong>Cenário de uso</strong>: Sistemas multitarefa onde diferentes processos podem acessar recursos em ordens variadas.</li>



<li><strong>Vantagens</strong>: Previne deadlocks sem necessidade de mecanismos complexos de verificação.</li>



<li><strong>O que é</strong>: Impõe uma ordem fixa de bloqueio de recursos, garantindo que todas as tarefas sigam a mesma sequência ao acessá-los.</li>
</ul>



<h2 class="wp-block-heading"><strong>5. Padrões de Distribuição e Comunicação</strong></h2>



<p class="wp-block-paragraph">Os padrões desta categoria garantem uma comunicação eficiente entre diferentes partes do sistema, seja dentro de um único microcontrolador ou entre múltiplos dispositivos conectados em rede. Eles ajudam a estruturar a troca de informações de forma confiável e escalável.</p>



<h3 class="wp-block-heading"><strong>5.1 Shared Memory Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Comunicação ineficiente entre tarefas devido ao uso de filas ou mensagens que geram sobrecarga.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que precisam compartilhar grandes volumes de dados entre múltiplas tarefas ou processadores.</li>



<li><strong>Vantagens</strong>: Baixa latência e alta taxa de transferência de dados.</li>



<li><strong>O que é</strong>: Um espaço de memória compartilhado é utilizado como meio de comunicação entre processos, evitando a necessidade de cópias de dados desnecessárias.</li>
</ul>



<h3 class="wp-block-heading"><strong>5.2 Remote Method Call Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Comunicação entre processos distribuídos sem uma interface de baixo nível bem definida.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que se comunicam via redes como CAN, Modbus ou Ethernet.</li>



<li><strong>Vantagens</strong>: Oculta a complexidade da comunicação e facilita a implementação de chamadas remotas.</li>



<li><strong>O que é</strong>: Permite que um processo invoque funções em outro sistema remoto como se fossem chamadas locais.</li>
</ul>



<h3 class="wp-block-heading"><strong>5.3 Observer Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Comunicação ineficiente entre módulos que precisam ser notificados sobre mudanças de estado.</li>



<li><strong>Cenário de uso</strong>: Sistemas de eventos, sensores e notificações em tempo real.</li>



<li><strong>Vantagens</strong>: Reduz o acoplamento entre os módulos e melhora a escalabilidade do sistema.</li>



<li><strong>O que é</strong>: Define um mecanismo de notificação assíncrona onde múltiplos observadores podem ser informados sobre mudanças de estado de um único sujeito.</li>
</ul>



<h3 class="wp-block-heading"><strong>5.4 Data Bus Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Comunicação complexa e desorganizada entre múltiplos módulos do sistema.</li>



<li><strong>Cenário de uso</strong>: Arquiteturas de sistemas embarcados que exigem comunicação padronizada entre diversos componentes.</li>



<li><strong>Vantagens</strong>: Centraliza a comunicação, reduz a complexidade e melhora a modularidade.</li>



<li><strong>O que é</strong>: Implementa um barramento de dados onde múltiplos componentes podem publicar e assinar mensagens de forma padronizada.</li>
</ul>



<h3 class="wp-block-heading"><strong>5.5 Proxy Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Comunicação ineficiente e insegura entre componentes distribuídos ou remotos.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que utilizam interfaces de comunicação externas ou protocolos remotos.</li>



<li><strong>Vantagens</strong>: Melhora a segurança, reduz a latência e otimiza a comunicação entre módulos separados.</li>



<li><strong>O que é</strong>: Um intermediário que atua como representante de outro objeto, fornecendo uma interface simplificada e segura para acessá-lo.</li>
</ul>



<h3 class="wp-block-heading"><strong>5.6 Broker Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Dependência direta entre módulos que precisam trocar informações de forma distribuída.</li>



<li><strong>Cenário de uso</strong>: Sistemas de comunicação assíncrona, como IoT e redes industriais.</li>



<li><strong>Vantagens</strong>: Desacopla os módulos e permite escalabilidade na comunicação.</li>



<li><strong>O que é</strong>: Introduz um broker (intermediário) que gerencia a comunicação entre diferentes partes do sistema sem que elas precisem conhecer diretamente umas às outras.</li>
</ul>



<h2 class="wp-block-heading"><strong>6. Padrões de Segurança e Confiabilidade</strong></h2>



<p class="wp-block-paragraph">Os padrões desta categoria garantem que o sistema continue operando de forma segura e confiável mesmo diante de falhas de hardware, software ou interferências externas. Eles são especialmente importantes em sistemas críticos, como automação industrial, aeroespacial e dispositivos médicos.</p>



<h3 class="wp-block-heading"><strong>6.1 Protected Single Channel Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falhas na comunicação entre módulos devido a corrupção de dados.</li>



<li><strong>Cenário de uso</strong>: Sistemas que transmitem dados críticos via barramentos compartilhados.</li>



<li><strong>Vantagens</strong>: Garante a integridade dos dados transmitidos.</li>



<li><strong>O que é</strong>: Implementa mecanismos de verificação, como CRC e checksum, para assegurar que as mensagens recebidas sejam íntegras.</li>
</ul>



<h3 class="wp-block-heading"><strong>6.2 Homogeneous Redundancy Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falhas em componentes críticos sem um sistema de backup imediato.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados de missão crítica, como aeronaves e equipamentos médicos.</li>



<li><strong>Vantagens</strong>: Aumenta a confiabilidade do sistema ao replicar funcionalidades críticas.</li>



<li><strong>O que é</strong>: Usa múltiplas instâncias idênticas de um componente para fornecer redundância e permitir recuperação automática em caso de falha.</li>
</ul>



<h3 class="wp-block-heading"><strong>6.3 Triple Modular Redundancy (TMR) Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Erros transitórios ou permanentes em hardware crítico.</li>



<li><strong>Cenário de uso</strong>: Sistemas de controle de segurança, como sensores de usinas nucleares e controle de motores em aeronaves.</li>



<li><strong>Vantagens</strong>: Aumenta a resiliência do sistema contra falhas de hardware.</li>



<li><strong>O que é</strong>: Utiliza três módulos independentes executando a mesma tarefa e um votador que decide o resultado correto com base no consenso entre os três.</li>
</ul>



<h3 class="wp-block-heading"><strong>6.4 Heterogeneous Redundancy Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falhas que afetam sistemas idênticos devido a vulnerabilidades comuns.</li>



<li><strong>Cenário de uso</strong>: Aplicações onde falhas sistêmicas devem ser evitadas a todo custo.</li>



<li><strong>Vantagens</strong>: Maior robustez contra falhas comuns.</li>



<li><strong>O que é</strong>: Usa diferentes implementações de um mesmo sistema para reduzir o risco de falhas sistêmicas.</li>
</ul>



<h3 class="wp-block-heading"><strong>6.5 Monitor-Actuator Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falta de monitoramento automático para detectar falhas antes que causem danos ao sistema.</li>



<li><strong>Cenário de uso</strong>: Sistemas que precisam garantir operação contínua sem intervenção humana constante.</li>



<li><strong>Vantagens</strong>: Aumenta a resiliência do sistema.</li>



<li><strong>O que é</strong>: Implementa sensores e atuadores que monitoram o estado do sistema e tomam ações preventivas quando necessário.</li>
</ul>



<h3 class="wp-block-heading"><strong>6.6 Sanity Check Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Comportamento imprevisível do sistema devido a erros internos ou falhas não detectadas.</li>



<li><strong>Cenário de uso</strong>: Sistemas embarcados que precisam garantir um funcionamento previsível e seguro.</li>



<li><strong>Vantagens</strong>: Detecta erros rapidamente e evita falhas catastróficas.</li>



<li><strong>O que é</strong>: Implementa verificações automáticas que garantem que o sistema esteja operando dentro dos parâmetros esperados.</li>
</ul>



<h3 class="wp-block-heading"><strong>6.7 Watchdog Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Travamento do sistema devido a loops infinitos ou falhas inesperadas.</li>



<li><strong>Cenário de uso</strong>: Qualquer sistema embarcado onde a operação contínua deve ser garantida.</li>



<li><strong>Vantagens</strong>: Melhora a estabilidade e recuperação do sistema.</li>



<li><strong>O que é</strong>: Utiliza um temporizador de supervisão (watchdog) que reinicia o sistema se uma falha for detectada.</li>
</ul>



<h3 class="wp-block-heading"><strong>6.8 Safety Executive Pattern</strong></h3>



<ul class="wp-block-list">
<li><strong>Problema que resolve</strong>: Falha na tomada de decisões de segurança em sistemas críticos.</li>



<li><strong>Cenário de uso</strong>: Sistemas de segurança industrial e dispositivos médicos.</li>



<li><strong>Vantagens</strong>: Melhora a confiabilidade e a resposta a falhas.</li>



<li><strong>O que é</strong>: Implementa um mecanismo de supervisão que avalia continuamente os riscos e toma ações para evitar falhas graves.</li>
</ul>



<h2 class="wp-block-heading"><strong>7. Conclusão</strong></h2>



<p class="wp-block-paragraph">Os padrões de projeto desempenham um papel fundamental no desenvolvimento de sistemas embarcados eficientes, seguros e escaláveis. Cada categoria de padrões abordada neste artigo fornece soluções estruturadas para problemas recorrentes, desde a organização da arquitetura até o gerenciamento de concorrência, memória, recursos, comunicação e segurança.</p>



<p class="wp-block-paragraph">A escolha adequada dos padrões a serem utilizados em um projeto pode impactar diretamente na modularidade, desempenho e confiabilidade do sistema embarcado. Implementar esses padrões corretamente pode reduzir a complexidade do código, melhorar a manutenibilidade e garantir que o software funcione de forma previsível, mesmo em cenários críticos.</p>



<p class="wp-block-paragraph">Nos próximos artigos desta série, exploraremos cada padrão em detalhes, apresentando exemplos práticos e sua aplicação em C para sistemas embarcados. Assim, engenheiros e desenvolvedores poderão aplicar esses conceitos de maneira eficaz em seus projetos.</p><p>The post <a href="https://mcu.tec.br/linguagem/c/padroes-de-projeto-para-sistemas-embarcados-em-c/">Padrões de Projeto para Sistemas Embarcados em C</a> first appeared on <a href="https://mcu.tec.br">MCU & FPGA</a>.</p>]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">69</post-id>	</item>
	</channel>
</rss>
