Erlang OTP: Distributed & Fault-Tolerant Systems Programming · บทเรียน

GenStatem สำหรับการจัดการสถานะ

เชี่ยวชาญ GenStatem เพื่อสร้างเครื่องสถานะจำกัดที่แข็งแกร่ง จัดการการเปลี่ยนสถานะซับซ้อน และรับมือกับเหตุการณ์ได้อย่างมีประสิทธิภาพ

บทเรียน 1 จาก 411 ขั้นตอน

GenStatem สำหรับการจัดการสถานะ เป็นบทเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Erlang OTP: Distributed & Fault-Tolerant Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Meet GenStatem

Welcome to GenStatem! It's an OTP behavior in Erlang used to build Finite State Machines (FSMs). If your system component needs to behave differently based on its current state, GenStatem is your friend.

Think of it as a specialized tool for managing complex state logic, offering more explicit control over state transitions than a regular GenServer.

FSM Fundamentals

A Finite State Machine (FSM) is a mathematical model of computation that describes the behavior of a system. It can only be in one state at any given time.

  • States: Distinct conditions a system can be in (e.g., "on", "off", "idle", "active").
  • Events: Inputs or occurrences that trigger a change in state (e.g., "button_press", "timeout").
  • Transitions: Rules that define how an event in a particular state causes a shift to a new state.

GenStatem Module Basics

Like other OTP behaviors, GenStatem requires a callback module. This module implements specific functions that define the FSM's behavior.

The most basic function is init/1, which sets up the initial state and data for your FSM. It returns {:ok, InitialState, InitialStateData}.

-module(my_fsm).
-behaviour(gen_statem).

-export([start_link/0]).
-export([init/1]).
-export([callback_mode/0]).

% Minimal init for a GenStatem
init(_Args) ->
    io:format("FSM initializing...~n"),
    InitialState = off, % Our first state
    InitialStateData = [], % Any data we want to carry
    {:ok, InitialState, InitialStateData}.

% Defines how events are handled (state-name based)
callback_mode() ->
    state_functions.

start_link() ->
    gen_statem:start_link({local, ?MODULE}, ?MODULE, [], []).

States and StateData

In GenStatem, a state is typically an atom (e.g., :on, :off). StateData is any Erlang term that holds the internal information associated with the current state, similar to a GenServer's state.

When you transition, you specify both the new state atom and the new state data. This allows you to carry context and information across different states of your FSM.

Responding to Events

GenStatem uses callback functions to react to events. For asynchronous events (like gen_statem:cast/2), the handle_event/4 callback is used.

The function signature is State(EventType, EventContent, StateData), where State is the current state atom and EventType indicates the type of message (e.g., :cast, :info).

% Example for 'off' state
off(cast, toggle, StateData) ->
    io:format("Switching to ON from OFF~n"),
    {:next_state, on, StateData}; % Transition to 'on' state

off(info, _Msg, StateData) ->
    io:format("Received info in OFF state~n"),
    {:next_state, off, StateData}.

Changing States

The return value of your event-handling functions dictates the FSM's next action. To change state, you return a tuple: {:next_state, NewState, NewStateData}.

  • NewState: The atom representing the next state.
  • NewStateData: The updated state data to be carried into the new state.

If you want to stay in the current state, you can return {:keep_state, NewStateData} or {:keep_state_and_data} if data doesn't change.

Sync vs. Async Events

GenStatem handles different types of events:

  • handle_call/4: For synchronous calls (gen_statem:call/3). The caller waits for a reply.
  • handle_event/4: For asynchronous casts (gen_statem:cast/2) and internal messages (gen_statem:info/2, or process messages). The caller does not wait.
  • handle_info/4: A specialized version of handle_event for process messages not originating from gen_statem:cast or gen_statem:call. Often less used with state_functions mode.

We'll focus on handle_call and handle_event in our example.

Light Switch Example

Let's build a classic FSM: a light switch! It will have two states: off and on.

We'll send a toggle event to change its state. We'll also add a way to check its current status.

Light Switch Code

Here's the full Erlang module for our light switch. Run it and try interacting with it!

-module(light_switch).
-behaviour(gen_statem).

-export([start_link/0, toggle/0, status/0]).
-export([init/1, callback_mode/0]).
-export([off/4, on/4]). % Export state functions

% -- Public API --
start_link() ->
    gen_statem:start_link({local, ?MODULE}, ?MODULE, [], []).

toggle() ->
    gen_statem:cast(?MODULE, toggle).

status() ->
    gen_statem:call(?MODULE, status).

% -- GenStatem Callbacks --
init(_Args) ->
    io:format("Light switch initializing to OFF~n"),
    {:ok, off, []}. % Initial state 'off', no specific data

callback_mode() ->
    state_functions.

% -- State 'off' callbacks --
off(cast, toggle, StateData) ->
    io:format("Switching from OFF to ON~n"),
    {:next_state, on, StateData};
off(call, status, From, StateData) ->
    gen_statem:reply(From, off),
    {:keep_state, StateData};
off(EventType, EventContent, StateData) ->
    io:format("OFF state received unhandled event: ~p, ~p~n", [EventType, EventContent]),
    {:keep_state, StateData}.

% -- State 'on' callbacks --
on(cast, toggle, StateData) ->
    io:format("Switching from ON to OFF~n"),
    {:next_state, off, StateData};
on(call, status, From, StateData) ->
    gen_statem:reply(From, on),
    {:keep_state, StateData};
on(EventType, EventContent, StateData) ->
    io:format("ON state received unhandled event: ~p, ~p~n", [EventType, EventContent]),
    {:keep_state, StateData}.

% --- How to run this code in Erlang shell: ---
% c(light_switch).
% light_switch:start_link().
% light_switch:status(). % Should be 'off'
% light_switch:toggle().
% light_switch:status(). % Should be 'on'
% light_switch:toggle().
% light_switch:status(). % Should be 'off'

GenStatem Challenge

Consider a GenStatem module representing a door with states :closed and :open. It receives :open_door and :close_door events.

If the door is :closed and receives :open_door, it transitions to :open. If it's :open and receives :close_door, it transitions to :closed.

What is the correct return value from the closed/4 state function when it receives an :open_door event via gen_statem:cast/2?

GenStatem Summary

Great job mastering GenStatem!

You've learned that GenStatem is ideal for implementing Finite State Machines, allowing you to manage complex state-dependent logic. Key takeaways:

  • FSMs have states, events, and transitions.
  • GenStatem uses callback modules and state functions (e.g., off/4, on/4).
  • You transition between states using {:next_state, NewState, NewStateData}.
  • Events can be asynchronous (cast, handled by handle_event/4) or synchronous (call, handled by handle_call/4).

This powerful behavior is a cornerstone for building robust, predictable systems in Erlang.

เริ่มต้นได้ฟรี

เรียนรู้ Erlang ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

คำถามที่พบบ่อย

บทเรียน “GenStatem สำหรับการจัดการสถานะ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “GenStatem สำหรับการจัดการสถานะ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Erlang OTP: Distributed & Fault-Tolerant Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Erlang OTP: Distributed & Fault-Tolerant Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “GenStatem สำหรับการจัดการสถานะ”

เชี่ยวชาญ GenStatem เพื่อสร้างเครื่องสถานะจำกัดที่แข็งแกร่ง จัดการการเปลี่ยนสถานะซับซ้อน และรับมือกับเหตุการณ์ได้อย่างมีประสิทธิภาพ คุณปฏิบัติ Erlang OTP: Distributed & Fault-Tolerant Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Erlang OTP: Distributed & Fault-Tolerant Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “GenStatem สำหรับการจัดการสถานะ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming นี้ได้ไหม

ได้ บทเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. GenStatem สำหรับการจัดการสถานะ
  2. GenEvent สำหรับการจัดการเหตุการณ์
  3. พฤติกรรม OTP แบบกำหนดเอง
  4. การสลับโค้ดแบบร้อนและการอัปเกรดขณะทำงาน
← กลับไปที่ Erlang OTP: Distributed & Fault-Tolerant Systems Programming