CondCreate
 
创建用于同步线程的条件变量

语法

Declare Function CondCreate ( ) As Any Ptr

用法

result = CondCreate

返回值

新创建的条件变量的句柄,或失败时的空指针(0)。

说明

一旦条件是Condcreated并且线程被启动,其中一个或多个可以被设置为条件的CondWait,它们将被停止,直到其他线程CondSignal等待线程可以重新启动。可以使用CondBroadcast重新启动等待条件的所有线程(包括执行主程序的主线程)。必须在程序结束时使用CondDestroy以避免在操作系统中泄露资源。

例子

''
''使新创建的线程等待所有线程准备好,然后立即启动它们
''

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差别

  • 新的FreeBASIC

参考