雷鹏 发表于 2018-7-10 22:55:25

内存池使用

本帖最后由 雷鹏 于 2018-7-10 22:58 编辑

#include <rtthread.h>
/* 两个线程用到的TCB和栈 */
struct rt_thread thread1;
struct rt_thread thread2;
char thread1_stack;
char thread2_stack;
/* 内存池数据存放区域 */
char mempool;
/* 内存池TCB */
struct rt_mempool mp;
/* 测试用指针分配头 */
char *ptr;
/* 测试线程1入口 */
void thread1_entry( void* parameter )
{
int i;
char *block;
while( 1 )
{
    /* 分配48个内存块 */
    for ( i = 0; i < 48; i++ )
    {
      rt_kprintf( "allocate No.%d\n", i );
      ptr = rt_mp_alloc( &mp, RT_WAITING_FOREVER );
    }
    /* 再分配一个内存块 */
    block = rt_mp_alloc( &mp, RT_WAITING_FOREVER );
    rt_kprintf( "allocate the block mem\n" );
    /* 是否分配的内存块 */
    rt_mp_free( block );
    block = RT_NULL;
rt_thread_delay(300);      
}
}
/* 测试线程2入口 */
void thread2_entry( void *parameter )
{
int i;
while( 1 )
{
   
    /* 释放48个已经分配的内存块 */
    for ( i = 0 ; i < 48; i ++ )
    {
      /* 非空才释放 */
      if ( ptr != RT_NULL )
      {
                        rt_kprintf( "try to release block\n" );
      rt_kprintf( "release block %d\n", i );
      rt_mp_free( ptr );
      /* 释放完成,把指针清零 */
      ptr = RT_NULL;
      }
    }
rt_thread_delay(300);
               
}
}
int rt_application_init()
{
int i;
for ( i = 0; i < 48; i ++ ) ptr = RT_NULL;
/* 初始化一个内存池对象,每个内存块的大小是80个字节 */
rt_mp_init( &mp, "mp1", &mempool,
            sizeof( mempool ), 80 );
/* 初始化两个测试线程对象 */
rt_thread_init( &thread1,
                  "thread1",
                  thread1_entry, RT_NULL,
                  &thread1_stack, sizeof( thread1_stack ),
                  20, 10 );
rt_thread_init( &thread2,
                  "thread2",
                  thread2_entry, RT_NULL,
                  &thread2_stack, sizeof( thread2_stack ),
                  25, 7 );
rt_thread_startup( &thread1 );
rt_thread_startup( &thread2 );
return 0;
}

页: [1]
查看完整版本: 内存池使用