SyncProvideCriticalSection - Create and initialize a critical section block in memory

Top  Previous  Next

Syntax

 

SyncProvideCriticalSection( @<nCriticalSection> )

 

Parameters

 

<nCriticalSection>

 

This parameter refers to an address in memory at which a critical section info block is stored. It must be passed by reference. If it is NIL on call, a critical section info block is created in memory and initialized. This block's address is returned in <nCriticalSection>. If it is a numeric value, SyncProvideCriticalSection will do nothing because it assumes the critical section info block has already been created and initialized.

 

Return value

 

Always NIL.

 

Description

 

SyncProvideCriticalSection will provide an info block that can be used by Windows' critical section functions. It can also be used by Cockpit's SYNC FUNCTIONs which use critical sections for synchronization. You should use this function to create a critical section if creation could happen in two separate threads at the same time.

 

Classification

 

Core

 

Category

 

Synchronization

 

Quick Info

 

Library: cckptcor.lib / cckptcor.dll

 

See also

 

Synchronization

 

Example

 

 

#INCLUDE "CockpitPlatformLibs.ch"

 

* This list will hold some keydata.

* Access to it is synchronized with a critical section.

STATIC list := {}

 

 

* Her goes our code...

FUNCTION main

 

LOCAL t1,t2,n

 

* Start two concurring threads adding the numbers 1 to 1000 to the list

* Give the threads the ids "A" and "B"

t1 := Thread():New():Start({||Add1to1000("A")})

t2 := Thread():New():Start({||Add1to1000("B")})

 

* Wait two seconds

WinSleep(2000)

 

* Display all list elements

FOR n := 1 TO Len(list)

   ?? list[n]

NEXT n

 

RETURN NIL

 

 

* Add the numbers 1 to 1000 to our list

FUNCTION Add1to1000(tid)

 

LOCAL n

 

FOR n := 1 TO 1000

   AddNewOnesOnly(n,tid)

NEXT n

 

RETURN NIL

 

 

* Add an element to our list if it has not been added before

FUNCTION AddNewOnesOnly(value,tid)

 

* This will become the critical section info

STATIC cs

 

* Transform the value to allow adding the thread identifier later

LOCAL addval := Str(value,4,0)

 

* Provide a crtitcal section info if it's hasn't been created before

SyncProvideCriticalSection(@cs)

 

* Enter the critical section

EnterCriticalSection(cs)

 

  * AScan and AAdd must be executed without being interrupted by a different

  * thread doing the same thing, otherwise duplicate elements could occur

  IF AScan(list,{|elem|SubStr(elem,1,4)==addval}) == 0

     AAdd(list,addval + "-" + tid)

  ENDIF

 

* Leave the critical section

LeaveCriticalSection(cs)

 

RETURN NIL