0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

mallocにNUMA APIのmbindを適用させる方法

Last updated at Posted at 2025-03-22

何故mmapじゃダメか

mmapで確保された領域はmunmapによりOSに返還されますがこれだと再度割り当てた際にマイナーフォルトなどにより非常に効率の悪い処理になってしまうことがあります。
mallocはfreeが呼び出された後メモリプールなどでメモリ領域を管理していることが多く, こうした問題を回避しています。

エラーが起きる時

以下のようなコードだとエラーが起きます。

void *ptr = (void *)malloc(size);
unsigned long nodemask = 1 << 0;
if (mbind(ptr, size, MPOL_PREFERRED, &nodemask, sizeof(nodemask) * 8, 0) != 0){
    perror("mbind failed");
}

これはmbindのdocsにもある通りmbindは基本的にmmapで割り当てた領域を対象に作用するためです。しかしながら, どうにかしてmallocでも使う方法はないでしょうか, mallocでも一部のallocateはmmapのはずなのにどうして使えないのでしょうかと思いませんでしょうか?

mbindが作用する時

mmapはページサイズの倍数アドレスが返されるので, mbindはどうもalignされたアドレスを想定しているっぽいのでaligned_allocを使うと動きます

void *ptr = (void *)aligned_alloc(PAGE_SIZE, size);
unsigned long nodemask = 1 << 0;
if (mbind(ptr, size, MPOL_PREFERRED, &nodemask, sizeof(nodemask) * 8, 0) != 0){
    perror("mbind failed");
}

一応これで動きましたがaligned_allocの実装次第では想定してない挙動になるかもしれません。実験ではjemallocのaligned_allocを用いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?