LoginSignup
3
0

More than 1 year has passed since last update.

C言語におけるBoehmGCの利用(備忘録)

Last updated at Posted at 2018-10-09

勉強がてら,C言語上でGarbage Collectionを利用することができるBohem GCの導入方法を記載します.
C言語上でBohem GCを導入することで,手動メモリ管理(malloc)を使う代わりに,自動的にメモリ管理を行うことができます.
もちろん,そのトレードオフとしてGCによる停止時間があることは留意してください.また,本記事では"保守的なGC (conservative GC)"や"正確なGC (precise GC)"については解説しません.

想定読者

  • C言語, GCをある程度知っている人
  • C言語で気軽にGC利用したい人 => free()を書きたくない/メモリ管理したくない人

実行環境

OS :Ubuntu 22.04.2 LTS
compiler : gcc version 11.3.0 (Ubuntu 11.3.0-1ubuntu1~22.04)

$ lsb_release -a 
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 22.04.2 LTS
Release:	22.04
Codename:	jammy
$ gcc --version
gcc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
...

導入

  • ソースコードの入手とビルド
    BohemGCに従い,以下のコマンドを実行する.このとき git, automake, autoconf, libtoolなどはインストールしておく必要がある.
$ sudo apt-get install autoconf automake libtool
$ mkdir testBohemGC && cd $_
$ git clone git://github.com/ivmai/libatomic_ops.git
$ git clone git://github.com/ivmai/bdwgc.git
$ ln -s  [AbsolutePath]/libatomic_ops [AbsolutePath]/bdwgc/libatomic_ops
$ cd bdwgc
$ autoreconf -vif
$ automake --add-missing
$ ./configure
$ make
$ sudo make install

これで準備は終わり.

実行

メモリ管理が必要なC言語プログラムを用意する.
プログラミング言語: 保守的GCを使ってみるのarray.cサンプルとします
参照先にも書いてありますが,callocの部分はGC_mallocに書き換えが必要(伴いgc/gc.hも追加).

$ gcc array.c -lgc
$ ./a.out
object size = 1000 bytes
array length = 12345
iterations = 123456
minimum = 8 * 12345 + 1000 * 12345 = 12443760
total alloc = 8 * 12345 + 1000 x 123456 = 123554760
0.291509 sec for 123456 allocs (2361.237308 nsec per alloc)

教えてほしい部分

  • 正確なGCを実行するための変換器 Magpieをコンパイルできた方いましたら教えてください.
3
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
3
0