...ing logging 4.0

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

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

適切に synchronized ブロックを使えば利用者側で気をつける必要がなくなる.
クラスメンバの中での synchronized は synchronized (this) と同じ.

import std.stdio;
import core.thread;

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

void main()
{
	auto bank = new 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();
}