17
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

スレッドにアフィニティを設定する

Last updated at Posted at 2013-07-28

プログラムを書いてて、ベンチマーク時にノイズを除去するためにプロセスにアフィニティを設定したいという状況に遭遇したりします。
アフィニティというのは「このプロセスは2番4番7番目のCPUコアの上でしか実行しないで!」のようにOSに対し明示的に設定するものです。
普通にググってもそのものズバリのサンプルコードがなかったのでここに。

/* ↓実はこのdefineが無いとshed.hの中身が有効にならない */
# define _GNU_SOURCE 1
# include <sched.h>

void* work(void* ) {
  cpu_set_t mask;  // 実行可能なCPUをビットマスクで指定する
  CPU_ZERO(&mask);  // まずマスクを全部オフにして
  CPU_SET(TID, &mask);  // TID番目のコアでのみ実行を許可する
  if (sched_setaffinity(0, sizeof(mask), &mask) == -1) {  // アフィニティを設定
    perror("setaffinity:");
    exit(1);
  }
  // ここにコードを書く
}

defineの所がわからずに失敗し続けてハマった。

17
16
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
17
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?