รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ
เรียนรู้การใช้กลไกพื้นฐานด้านการทำงานพร้อมกันของ Clojure เพื่อจัดการสถานะที่เปลี่ยนแปลงได้อย่างปลอดภัยระหว่างเธรด
รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ เป็นบทเรียน Clojure Functional Programming & JVM Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Clojure Functional Programming & JVM Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Clojure Functional Programming & JVM Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Concurrency & State Intro
Managing state in concurrent programs is tricky! When multiple parts of your code try to change the same data at once, you can run into big problems like data corruption or deadlocks.
Clojure offers powerful tools to handle shared mutable state safely and efficiently.
Clojure's State Philosophy
Clojure embraces immutability by default. This means data structures don't change after creation. But what about when you genuinely need to change something, like a counter or a user's balance?
- Clojure provides special concurrency primitives.
- These primitives manage mutable state in a controlled way.
- They ensure changes are safe, even across multiple threads.
Atoms: Independent State
An Atom is the simplest way to manage a single, independent piece of mutable state. It's great for things like counters or flags.
- Updates are synchronous and atomic (all-or-nothing).
- Atoms use a Compare-And-Swap (CAS) loop internally.
- Best for state that doesn't need to be coordinated with other pieces of state.
Atom Code Example
Let's see an Atom in action. We'll create a simple counter and update it.
(ns coddykit.core
(:gen-class))
(defn -main
"Demonstrates Clojure Atoms."
[& args]
(let [my-counter (atom 0)]
(println "Initial value:" @my-counter)
(swap! my-counter inc)
(println "After inc:" @my-counter)
(swap! my-counter + 5)
(println "After add 5:" @my-counter)))Atom `swap!` Explained
The swap! function is key for updating Atoms:
- It takes the atom, a function, and optional arguments for that function.
(swap! my-atom inc)atomically increments the value.(swap! my-atom + 5)atomically adds 5 to the value.- The function is applied to the atom's current value, and the result becomes the new value. This happens in a thread-safe way.
Refs: Coordinated State
Refs are for managing coordinated mutable state. This means you have multiple pieces of state that must change together, or not at all.
- Refs use Clojure's Software Transactional Memory (STM).
- Changes occur within a transaction (
dosyncblock). - All changes in a transaction either succeed or fail as a group.
Ref Code Example
Here's how to use Refs to transfer a value between two accounts atomically. If one fails, both revert.
(ns coddykit.core
(:gen-class))
(defn -main
"Demonstrates Clojure Refs and STM."
[& args]
(let [account-a (ref 100)
account-b (ref 50)
amount-to-transfer 20]
(println "Initial: A=" @account-a "B=" @account-b)
(dosync
(alter account-a - amount-to-transfer)
(alter account-b + amount-to-transfer))
(println "After transfer: A=" @account-a "B=" @account-b)))STM with Refs Explained
The dosync block defines a transaction:
refcreates a new Ref.alterchanges a Ref's value within a transaction. It takes the Ref, a function, and its arguments.- If any part of the
dosyncblock fails, all changes are rolled back. - This ensures atomicity: all or nothing.
Agents: Asynchronous State
Agents are designed for managing mutable state asynchronously and in isolation. They're perfect for tasks that might take time or run in the background without blocking your main thread.
- Updates are sent as messages to the Agent.
- The Agent processes these messages in a separate thread.
- This provides isolation: the agent's state changes only through its own processing.
Agent Code Example
Let's use an Agent to process a list of numbers asynchronously, summing them up.
(ns coddykit.core
(:gen-class))
(defn -main
"Demonstrates Clojure Agents."
[& args]
(let [sum-agent (agent 0)]
(println "Initial sum:" @sum-agent)
(send sum-agent + 10)
(send sum-agent + 20)
(send sum-agent + 5)
(println "Waiting for agent to finish...")
(await sum-agent) ; Wait for all sent actions to complete
(println "Final sum:" @sum-agent)))Agent Workflow
Here's how Agents work:
agentcreates a new Agent with an initial value.senddispatches a function and arguments to the agent. The function will be applied to the agent's current state on another thread.- The agent processes messages one by one in its own thread, ensuring isolated updates.
await(orawait-for) is used to block the current thread until the agent has processed all pending actions.
Choosing the Right Primitive
You've learned about Atoms, Refs, and Agents. Each has a specific purpose for managing mutable state safely.
Which of the following statements correctly describe when to use which concurrency primitive?
Recap: State Management
In this lesson, we explored Clojure's core concurrency primitives for managing mutable state safely:
- Atoms: For simple, independent, synchronous state changes.
- Refs: For coordinated, transactional state changes across multiple values using STM.
- Agents: For asynchronous, isolated state updates, processed in a separate thread.
Understanding these tools is crucial for building robust and concurrent Clojure applications!
คำถามที่พบบ่อย
บทเรียน “รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clojure Functional Programming & JVM Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clojure Functional Programming & JVM Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ”
เรียนรู้การใช้กลไกพื้นฐานด้านการทำงานพร้อมกันของ Clojure เพื่อจัดการสถานะที่เปลี่ยนแปลงได้อย่างปลอดภัยระหว่างเธรด คุณปฏิบัติ Clojure Functional Programming & JVM Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clojure Functional Programming & JVM Backend Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clojure Functional Programming & JVM Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Clojure Functional Programming & JVM Backend Development นี้ได้ไหม
ได้ บทเรียน Clojure Functional Programming & JVM Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ
- หน่วยความจำธุรกรรมซอฟต์แวร์ (STM)
- พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส
- Channel และบล็อก Go ของ core.async