__mt_alloc源码分析(10)

__pool<true>::_M_reserve_block

最后,当线程自己的空闲块没有的时候,__mt_alloc必须向内存池的全局空闲块链表求援,于是进入了_M_reserve_block函数。

 

<mt_allocator.cc>

312    char*

313    __pool<true>::_M_reserve_block(size_t __bytes, const size_t __thread_id)

 

_M_reserve_block函数原型。返回值是直接给用户使用的块的数据区地址,参数__bytes是用户要求分配的内存的字节大小,__thread_id是分配内存的线程的id

 

314    {

315      // Round up to power of 2 and figure out which bin to use.

316      const size_t __which = _M_binmap[__bytes];

317      const _Tune& __options = _M_get_options();

318      const size_t __bin_size = ((__options._M_min_bin << __which)

319                    + __options._M_align);

320      size_t __block_count = __options._M_chunk_size - sizeof(_Block_address);

321      __block_count /= __bin_size;     

 

进行一些前期计算,__which是负责分配内存的bin的索引,而__bin_size 是这个bin负责的最大的内存字节数。__options包含当前内存池的一些参数,__block_count表示从OS申请的一块内存(__pool每次总是从OS申请大小为__options._M_chunk_size的内存块)能建造多少个空闲内存块。

 

322     

323      // Are we using threads?

324      // - Yes, check if there are free blocks on the global

325      //   list. If so, grab up to __block_count blocks in one

326      //   lock and change ownership. If the global list is

327      //   empty, we allocate a new chunk and add those blocks

328      //   directly to our own freelist (with us as owner).

329      // - No, all operations are made directly to global pool 0

330      //   no need to lock or change ownership but check for free

331      //   blocks on global list (and if not add new ones) and

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值