pjsip内存池的使用


    内存池的使用相当的简单,扳个手指头就搞定了,如果你看明白了上面的原理和特征:)

     a).创建内存池工厂[Create Pool Factory]
    PJLIB已经有了一个默认的实现:Caching Pool Factory,这个内存池工厂的初始化使用函数pj_caching_pool_init()

    
    b).创建内存池[Create The Pool]
   使用pj_pool_create(),其参数分别为内存工厂(Pool Factory),内存池的名字(name),
始时的大小以及增长时的大小.
   
    c).根据需要分配内存[Allocate Memory as Required]
    然后,你就可以使用pj_pool_alloc(), pj_pool_calloc(), pj_pool_zalloc()从指定
的内存池根据需要去获取内存了:)
   
    d).Destroy内存池[Destroy the Pool]
     这实际上是把预分配的内存还给系统.
  
    e).Destroy内存池工厂[Destroy the Pool Factory]
   这没什么好说的.
   
    很简单吧:)
  作者在文档中给出了一个例子:
  如下:
#include <pjlib.h>

   #define THIS_FILE    "pool_sample.c"

   static void my_perror(const char *title, pj_status_t status)
   {
        char errmsg[PJ_ERR_MSG_SIZE];

        pj_strerror(status, errmsg, sizeof(errmsg));
        PJ_LOG(1,(THIS_FILE, "%s: %s [status=%d]", title, errmsg, status));
   }

   static void pool_demo_1(pj_pool_factory *pfactory)
   {
        unsigned i;
        pj_pool_t *pool;

        // Must create pool before we can allocate anything
        pool = pj_pool_create(pfactory,  // the factory
                              "pool1",   // pool's name
                              4000,      // initial size
                              4000,      // increment size
                              NULL);     // use default callback.
        if (pool == NULL) {
            my_perror("Error creating pool", PJ_ENOMEM);
            return;
        }

        // Demo: allocate some memory chunks
        for (i=0; i<1000; ++i) {
            void *p;

            p = pj_pool_alloc(pool, (pj_rand()+1) % 512);

            // Do something with p
            ...

            // Look! No need to free p!!
        }

        // Done with silly demo, must free pool to release all memory.
        pj_pool_release(pool);
   }

   int main()
   {
        pj_caching_pool cp;
        pj_status_t status;

        // Must init PJLIB before anything else
        status = pj_init();
        if (status != PJ_SUCCESS) {
            my_perror("Error initializing PJLIB", status);
            return 1;
        }

        // Create the pool factory, in this case, a caching pool,
        // using default pool policy.
        pj_caching_pool_init(&cp, NULL, 1024*1024 );

        // Do a demo
        pool_demo_1(&cp.factory);

        // Done with demos, destroy caching pool before exiting app.
        pj_caching_pool_destroy(&cp);

        return 0;
   }

猜你喜欢

转载自blog.csdn.net/a843538946/article/details/7067200