...ing logging 4.0

はてなブログに移行しました。D言語の話とかいろいろ。

スレッドセーフな銀行クラス(2)

すべてのメソッドの内容を synchronized ブロックに含めるのならクラスを synchronized クラスにしてもよい.
synchronized クラスのメンバはそのインスタンスを shared 型で生成しなければ呼び出せないので,この場合には new Bank ではなく new shared(Bank) とする.

import std.stdio;
import core.thread;

synchronized class Bank
{
	private int money_;
	
	void payin(int m)
	{
		money_ += m;
	}
	void payout(int m)
	{
		// お金があるときだけ出金する
		if (money_ - m > 0)
		{
			money_ -= m;
		}
		if (money_ < 0)
		{
			// ここには来ない
			throw new Exception("pay out exception.");
		}
	}
	int money() @property
	{
		return money_;
	}
}

void main()
{
	auto bank = new shared(Bank);
	auto tg = new ThreadGroup;
	bool isRunning = true;
	
	// 100ずつ出金する人
	tg.create = {
		while (isRunning)
		{
			try
			{
				bank.payout(100);
			}
			catch (Exception e)
			{
				isRunning = false; // 両方のスレッドを終了する
				throw e;
			}
		}
	};
	
	// 100ずつ入金する人
	tg.create = {
		while (isRunning)
		{
			bank.payin(100);
		}
	};
	
	// スレッドを回す
	tg.joinAll();
}