File: timer_fizzbuzz.cpp

package info (click to toggle)
libfilezilla 0.52.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,492 kB
  • sloc: cpp: 30,965; sh: 4,241; makefile: 375; xml: 37
file content (79 lines) | stat: -rw-r--r-- 1,904 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <libfilezilla/event_handler.hpp>
#include <libfilezilla/time.hpp>

#include <iostream>
#include <string>

struct interval_change_type;
typedef fz::simple_event<interval_change_type, fz::duration> interval_change;

class fizzbuzz final : public fz::event_handler
{
public:
	fizzbuzz(fz::event_loop& loop)
		: fz::event_handler(loop)
	{
		// Start two periodic timers
		fizz_ = add_timer(fz::duration::from_seconds(3), false);
		buzz_ = add_timer(fz::duration::from_seconds(5), false);
	}

	virtual ~fizzbuzz()
	{
		// This _MUST_ be called to avoid a race so that operator()(fz::event_base const&) is not called on a partially destructed object.
		remove_handler();
	}

private:
	virtual void operator()(fz::event_base const& ev)
	{
		// Dispatch the event to the correct function.
		fz::dispatch<fz::timer_event, interval_change>(ev, this, &fizzbuzz::on_timer, &fizzbuzz::on_interval_change);
	}

	void on_interval_change(fz::duration interval)
	{
		// We got told to change the woof interval.
		stop_timer(woof_);
		woof_ = add_timer(interval, false);
	}

	void on_timer(fz::timer_id const& id)
	{
		if (id == fizz_) {
			std::cout << "fizz" << std::endl;
		}
		else if (id == buzz_) {
			std::cout << "buzz" << std::endl;
		}
		else if (id == woof_) {
			std::cout << "woof" << std::endl;
		}
	}

	fz::timer_id fizz_{};
	fz::timer_id buzz_{};
	fz::timer_id woof_{};
};

int main()
{
	// Start an event loop and add a handler.
	fz::event_loop loop;
	fizzbuzz fb(loop);

	std::cout << "Enter interval in seconds for the woof timer or 0 to stop program." << std::endl;

	// Read numbers from stdin until reading fails or a 0 is entered
	int seconds;
	do {
		std::cin >> seconds;
		if (std::cin.good() && seconds > 0) {
			// Got a new interval, send to handler
			fb.send_event<interval_change>(fz::duration::from_seconds(seconds));
		}
	}
	while (std::cin.good() && seconds != 0);

	return 0;
}