一键导入
cangjie-concurrency
仓颉语言并发编程。当需要了解仓颉语言的M:N线程模型、spawn创建线程、sleep、原子操作(Atomic)、互斥锁(Mutex)、条件变量(Condition)、synchronized、Future、线程取消、ThreadLocal等特性时,应使用此 Skill。
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
仓颉语言并发编程。当需要了解仓颉语言的M:N线程模型、spawn创建线程、sleep、原子操作(Atomic)、互斥锁(Mutex)、条件变量(Condition)、synchronized、Future、线程取消、ThreadLocal等特性时,应使用此 Skill。
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
通用算法与数据结构实现参考——排序、搜索、动态规划、图算法、字符串处理的多语言惯用写法和模板代码(Python/C++/Java/Go/Cangjie)
仓颉语言算法与数据结构实现参考——排序、搜索、动态规划、图算法、字符串处理、集合操作的惯用写法和模板代码
仓颉编程语言基本概念和规则,当需要了解关键字、标识符、程序结构、变量定义(let/var/const)、值类型与引用类型、作用域规则、表达式(if/while/for-in/break/continue)、函数等基本概念时,应使用此 Skill
仓颉语言基本数据类型。当需要了解仓颉语言的整数、浮点、布尔、字符(Rune)、字符串(String)、Unit、Nothing、元组(Tuple)、数组(Array/VArray)、区间(Range)类型以及基本运算符的语法和规则时,应使用此 Skill。
仓颉程序与C程序互操作指导,包括foreign声明、CFunc、inout参数、unsafe块、调用约定、类型映射(基础类型/结构体/CPointer/VArray/CString)、C回调仓颉、内存管理等特性时,应使用此 Skill
仓颉语言类。当需要了解仓颉语言的类定义、抽象类、构造函数(init/主构造函数)、终结器(~init)、继承(单继承/sealed)、重写(override)、重定义(redef)、成员变量、成员函数、属性(prop)、访问修饰符、This类型、对象创建等特性时,应使用此 Skill。
| name | cangjie-concurrency |
| description | 仓颉语言并发编程。当需要了解仓颉语言的M:N线程模型、spawn创建线程、sleep、原子操作(Atomic)、互斥锁(Mutex)、条件变量(Condition)、synchronized、Future、线程取消、ThreadLocal等特性时,应使用此 Skill。 |
socket_read)时,整个原生线程被阻塞,阻止其调度其他仓颉线程 — 降低吞吐量spawn 关键字spawn { => ... } — 创建新的仓颉线程main(): Int64 {
spawn { =>
println("New thread before sleeping")
sleep(100 * Duration.millisecond)
println("New thread after sleeping")
}
println("Main thread")
return 0
}
sleep() 函数func sleep(dur: Duration): Unitdur 时长dur <= Duration.Zero,线程仅让出执行资源而不睡眠AtomicInt8、AtomicInt16、AtomicInt32、AtomicInt64、AtomicUInt8、AtomicUInt16、AtomicUInt32、AtomicUInt64AtomicBoolAtomicReference<T>(仅引用类型)| 操作 | 说明 |
|---|---|
load() | 读取值 |
store(val) | 写入值 |
swap(val) | 交换,返回旧值 |
compareAndSwap(old, new) | CAS:若当前值 == old,设为 new;返回 Bool |
fetchAdd(val) | 加法,返回旧值 |
fetchSub(val) | 减法,返回旧值 |
fetchAnd(val) | 按位与,返回旧值 |
fetchOr(val) | 按位或,返回旧值 |
fetchXor(val) | 按位异或,返回旧值 |
仅 load、store、swap、compareAndSwap
AtomicReference CAS 比较对象同一性(同一对象),非值相等Mutex)public class Mutex <: UniqueLock {
public init()
public func lock(): Unit
public func unlock(): Unit
public func tryLock(): Bool
public func condition(): Condition
}
unlock() 次数须与 lock() 次数匹配才能完全释放unlock() 抛出 IllegalSynchronizationStateExceptiontryLock() 返回 Bool — 不保证获取锁;须检查返回值Condition)public interface Condition {
func wait(): Unit
func wait(timeout!: Duration): Bool
func waitUntil(predicate: ()->Bool): Unit
func waitUntil(predicate: ()->Bool, timeout!: Duration): Bool
func notify(): Unit
func notifyAll(): Unit
}
Mutex 的 mtx.condition() 创建Condition 实例mtx.condition() 必须在 mutex 被锁定的状态下调用,如果在未锁定状态下调用,会抛出 IllegalSynchronizationStateExceptionimport std.sync.*
// ✅ 正确:在 synchronized 块中创建 Condition
let mtx = Mutex()
var cond: Condition = synchronized(mtx) {
mtx.condition()
}
// ✅ 正确:手动加锁后创建
let mtx2 = Mutex()
mtx2.lock()
let cond2 = mtx2.condition()
mtx2.unlock()
// ❌ 错误:未锁定状态下调用 condition()
// let mtx3 = Mutex()
// let cond3 = mtx3.condition() // 抛出 IllegalSynchronizationStateException
wait() 行为(4 步)notify() 或 notifyAll() 信号mtx.condition() 须在锁定状态下调用,否则抛出 IllegalSynchronizationStateExceptionwait()、notify()、notifyAll() 前须持有绑定的锁wait()wait(timeout) 超时精度不保证(依赖 OS)import std.sync.*
var ready = false
let mtx = Mutex()
// 在 synchronized 块中创建 Condition
let cond = synchronized(mtx) { mtx.condition() }
main() {
// 消费者线程
let consumer = spawn { =>
synchronized(mtx) {
while (!ready) { // 可避免虚假唤醒
cond.wait() // 等待通知
}
println("Consumer: data is ready!")
}
}
// 生产者线程
let producer = spawn { =>
sleep(Duration.second) // 模拟生产耗时
synchronized(mtx) {
ready = true
cond.notifyAll() // 唤醒所有等待线程
}
println("Producer: notified!")
}
consumer.get()
producer.get()
}
synchronized 关键字synchronized(lockInstance) {
// 临界区 — 自动加锁/解锁
}
break、continue、return、throw 退出Lock 实例(包括 Mutex)一起使用synchronized 是一个表达式,返回块的值ThreadLocal<T>)public class ThreadLocal<T> {
public init()
public func get(): Option<T> // 未设置时返回 None
public func set(value: Option<T>): Unit // 传 None 以删除
}
core 包(无需特殊导入)Future<T>.cancel():发送取消请求。不会强制停止线程Thread.currentThread.hasPendingCancellation:检查是否有取消请求SyncCounterSyncCounter(n),配合 dec() 和 waitUntilZero() 使用std.sync 包import std.sync.*
main() {
let counter = SyncCounter(3)
for (i in 0..3) {
spawn { =>
// 执行工作...
counter.dec() // 完成后计数减 1
}
}
counter.waitUntilZero() // 等待所有线程完成
}
Future<T> — 线程句柄public class Future<T> {
public func get(): T
public func get(timeout: Duration): T
public func tryGet(): Option<T>
}
spawn 返回 Future<T>,其中 T 匹配 Lambda 返回类型| 方法 | 行为 |
|---|---|
get() | 阻塞直到线程完成;返回结果。重新抛出线程中的异常 |
get(timeout) | 带超时阻塞;超时抛出 TimeoutException。若 timeout <= Duration.Zero,行为同 get() |
tryGet() | 非阻塞;线程未完成时返回 Option<T>.None;重新抛出异常 |
get() 的位置决定并发性:放在其他工作前串行化执行;放在之后允许并行Thread 类class Thread {
static prop currentThread: Thread
prop id: Int64
prop hasPendingCancellation: Bool
}
Thread 不能直接实例化Future<T>.thread 或 Thread.currentThread 获取id 是每个线程的唯一整数标识符