Download c source code

main:
	shared agent_sem := semaphore(1)
	shared match := semaphore(0)
	shared paper := semaphore(0)
	shared tobacco := semaphore(0)

	shared mutex := semaphore(1)
	shared is_match := false
	shared is_paper := false
	shared is_tobacco := false

	shared match_ready := semaphore(0)
	shared paper_ready := semaphore(0)
	shared tobacco_ready := semaphore(0)

	create_thread(agent)
	create_thread(smoker_with_matches)
	create_thread(smoker_with_paper)
	create_thread(smoker_with_tobacco)

	create_thread(pusher_match)
	create_thread(pusher_paper)
	create_thread(pusher_tobacco)


agent:
	create_thread(agent_without_matches)
	create_thread(agent_without_paper)
	create_thread(agent_without_tobacco)

agent_without_matches:
	while true do
		wait(agent_sem)
		signal(paper)
		signal(tobacco)

agent_without_paper:
	while true do
		wait(agent_sem)
		signal(match)
		signal(tobacco)

agent_without_tobacco:
	while true do
		wait(agent_sem)
		signal(match)
		signal(paper)


smoker_with_matches:
	while true do
		wait(match_ready)
		make_cigarette()
		signal(agent_sem)
		smoke()

smoker_with_paper:
	while true do
		wait(paper_ready)
		make_cigarette()
		signal(agent_sem)
		smoke()

smoker_with_tobacco:
	while true do
		wait(tobacco_ready)
		make_cigarette()
		signal(agent_sem)
		smoke()


pusher_match:
	while true do
		wait(match)

		wait(mutex)
		if is_paper then
			is_paper := false
			signal(match_ready)
		else if is_tobacco then
			is_tobacco := false
			signal(tobacco_ready)
		else
			is_match := true
		signal(mutex)

pusher_paper:
	while true do
		wait(paper)

		wait(mutex)
		if is_match then
			is_match := false
			signal(paper_ready)
		else if is_tobacco then
			is_tobacco := false
			signal(tobacco_ready)
		else
			is_paper := true
		signal(mutex)

pusher_tobacco:
	while true do
		wait(tobacco)

		wait(mutex)
		if is_match then
			is_match := false
			signal(paper_ready)
		else if is_paper then
			is_paper := false
			signal(match_ready)
		else
			is_tobacco := true
		signal(mutex)