创建用于同步线程的条件变量
语法
用法
result = CondCreate
返回值
新创建的条件变量的句柄,或失败时的空指针(0)。
说明
例子
''
''使新创建的线程等待所有线程准备好,然后立即启动它们
''
Dim Shared hcondstart As Any Ptr
Dim Shared hmutexstart As Any Ptr
Dim Shared start As Integer = 0
Dim Shared threadcount As Integer
Dim Shared hmutexready As Any Ptr
Dim Shared hcondready As Any Ptr
Sub mythread(ByVal id_ptr As Any Ptr)
Dim id As Integer = Cast(Integer, id_ptr)
Print "线程#" & id & "在等待..."
''表示该线程已准备就绪
MutexLock hmutexready
threadcount += 1
CondSignal hcondready
MutexUnlock hmutexready
''等待启动信号
MutexLock hmutexstart
Do While start = 0
CondWait hcondstart, hmutexstart
Loop
''现在这个线程在hmutexstart上保持锁定
MutexUnlock hmutexstart
''打印出这个线程的数量
For i As Integer = 1 To 40
Print id;
Next i
End Sub
Dim threads(1 To 9) As Any Ptr
hcondstart = CondCreate()
hmutexstart = MutexCreate()
hcondready = CondCreate()
hmutexready = MutexCreate()
threadcount = 0
For i As Integer = 1 To 9
threads(i) = ThreadCreate(@mythread, Cast(Any Ptr, i))
If threads(i) = 0 Then
Print "无法创建线程"
End If
Next i
Print "等待所有线程准备就绪"
MutexLock(hmutexready)
Do Until threadcount = 9
CondWait(hcondready, hmutexready)
Loop
MutexUnlock(hmutexready)
Print "Go!"
MutexLock hmutexstart
start = 1
CondBroadcast hcondstart
MutexUnlock hmutexstart
''等待所有线程完成
For i As Integer = 1 To 9
If threads(i) <> 0 Then
ThreadWait threads(i)
End If
Next i
MutexDestroy hmutexready
CondDestroy hcondready
MutexDestroy hmutexstart
CondDestroy hcondstart
平台差异
- Condcreate不适用于FreeBASIC的DOS版本/目标,因为DOS内核和所使用的扩展程序不支持多线程。
方言差异
与QB差别
参考