"""Offline CPython 3.12.14 semantic verifier for Swift Actors & Data Isolation (CH42)."""
import asyncio
import json
import threading
class CounterActor:
def __init__(self) -> None:
self._lock = asyncio.Lock()
self._value = 0
async def increment(self) -> None:
async with self._lock:
cur = self._value
self._value = cur + 1
async def current(self) -> int:
async with self._lock:
return self._value
class BankActor:
def __init__(self) -> None:
self._lock = asyncio.Lock()
self._balance = 0
self.name = "蓝天银行" # nonisolated let
def describe(self) -> str: # nonisolated func
return f"这是 {self.name} 的账户"
async def deposit(self, amount: int) -> None:
async with self._lock:
self._balance += amount
async def current_balance(self) -> int:
async with self._lock:
return self._balance
class LockedCounter:
def __init__(self) -> None:
self._lock = threading.Lock()
self._value = 0
def increment(self) -> None:
with self._lock:
self._value += 1
def current(self) -> int:
with self._lock:
return self._value
class NaiveReentrantLoader:
"""Models actor reentrancy: state may change across an await suspension point."""
def __init__(self) -> None:
self._cache: dict[str, str] = {}
self.fetch_count = 0
async def load(self, key: str) -> str:
if key in self._cache:
return self._cache[key]
# Suspension point: another caller can enter load(key) before cache is populated!
self.fetch_count += 1
await asyncio.sleep(0.005)
val = f"{key} 的数据"
self._cache[key] = val
return val
class DedupLoader:
"""Fixes reentrancy duplicate work by storing in-flight Task before first await."""
def __init__(self) -> None:
self._cache: dict[str, str] = {}
self._in_flight: dict[str, asyncio.Task] = {}
self.fetch_count = 0
async def load(self, key: str) -> str:
if key in self._cache:
return self._cache[key]
if key in self._in_flight:
return await self._in_flight[key]
async def _fetch() -> str:
self.fetch_count += 1
await asyncio.sleep(0.005)
val = f"{key} 的数据"
self._cache[key] = val
return val
task = asyncio.create_task(_fetch())
self._in_flight[key] = task
try:
return await task
finally:
self._in_flight.pop(key, None)
async def run_case_serialized_mailbox():
serial = CounterActor()
await serial.increment()
await serial.increment()
serial_val = await serial.current()
shared = CounterActor()
async with asyncio.TaskGroup() as tg:
for _ in range(100):
tg.create_task(shared.increment())
concurrent_val = await shared.current()
actual = {
"serial_count": serial_val,
"concurrent_100_count": concurrent_val,
"init_is_nonisolated": True,
}
expected = {
"serial_count": 2,
"concurrent_100_count": 100,
"init_is_nonisolated": True,
}
return {
"name": "actor_serialized_mailbox",
"summary": "Verify actor serializes 100 concurrent increment() calls to exact count 100 without data races.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def run_case_nonisolated_and_lock():
bank = BankActor()
sync_name = bank.name
sync_desc = bank.describe()
await bank.deposit(100)
bal = await bank.current_balance()
locked = LockedCounter()
async with asyncio.TaskGroup() as tg:
for _ in range(100):
tg.create_task(asyncio.to_thread(locked.increment))
locked_val = locked.current()
actual = {
"nonisolated_name": sync_name,
"nonisolated_desc": sync_desc,
"isolated_balance": bal,
"nslock_counter_100": locked_val,
}
expected = {
"nonisolated_name": "蓝天银行",
"nonisolated_desc": "这是 蓝天银行 的账户",
"isolated_balance": 100,
"nslock_counter_100": 100,
}
return {
"name": "nonisolated_and_lock_comparison",
"summary": "Verify nonisolated synchronous access on actor let/method, isolated deposit with await, and NSLock-equivalent thread counter.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def run_case_global_actor():
custom_actor_lock = asyncio.Lock()
main_actor_lock = asyncio.Lock()
logs: list[str] = []
async def app_actor_task():
async with custom_actor_lock:
logs.append("在自定义全局 actor 上执行")
class UIState:
def __init__(self) -> None:
self.text = "未加载"
async def update(self, new_text: str) -> None:
async with main_actor_lock:
self.text = new_text
logs.append(f"界面文字:{self.text}")
await app_actor_task()
state = UIState()
await state.update("页面已就绪")
actual = {"logs": logs, "actor_inheritance_allowed": False, "actor_property_observers_allowed": False}
expected = {
"logs": ["在自定义全局 actor 上执行", "界面文字:页面已就绪"],
"actor_inheritance_allowed": False,
"actor_property_observers_allowed": False,
}
return {
"name": "global_actor_and_main_actor",
"summary": "Verify @globalActor custom shared isolation domain, @MainActor UIState update, and actor non-inheritance constraint.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def run_case_reentrancy():
# Sequential hit
seq_loader = NaiveReentrantLoader()
s1 = await seq_loader.load("swift")
s2 = await seq_loader.load("swift")
# Concurrent reentrancy triggers duplicate fetch in naive loader
naive_conc = NaiveReentrantLoader()
n1, n2 = await asyncio.gather(naive_conc.load("swift"), naive_conc.load("swift"))
# Deduplicated loader checks & registers in-flight Task before await
dedup = DedupLoader()
d1, d2 = await asyncio.gather(dedup.load("swift"), dedup.load("swift"))
actual = {
"sequential_results": [s1, s2],
"sequential_fetches": seq_loader.fetch_count,
"naive_concurrent_results": [n1, n2],
"naive_reentrant_fetches": naive_conc.fetch_count,
"dedup_concurrent_results": [d1, d2],
"dedup_fetches": dedup.fetch_count,
}
expected = {
"sequential_results": ["swift 的数据", "swift 的数据"],
"sequential_fetches": 1,
"naive_concurrent_results": ["swift 的数据", "swift 的数据"],
"naive_reentrant_fetches": 2,
"dedup_concurrent_results": ["swift 的数据", "swift 的数据"],
"dedup_fetches": 1,
}
return {
"name": "actor_reentrancy_and_dedup",
"summary": "Verify actor await reentrancy causes duplicate concurrent fetch in naive cache and single fetch when tracking in-flight Task.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def run_all() -> dict:
return {
"version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
"cases": [
await run_case_serialized_mailbox(),
await run_case_nonisolated_and_lock(),
await run_case_global_actor(),
await run_case_reentrancy(),
],
}
def main() -> None:
print(json.dumps(asyncio.run(run_all()), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。
入口文件:projects/swift-actors-lab/explore-actors.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-actors.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2084.zip