THREADCOUNT function

Purpose

Return the number of PowerBASIC-created active threads that exist in a module.

Syntax

lCount& = THREADCOUNT

Remarks

Applications will return a THREADCOUNT of at least 1, which is attributed to the "primary" application thread.  Additional threads created by the application or module with the THREAD CREATE function will also be included in the tally returned by THREADCOUNT.

THREADCOUNT can be useful for when a "controlling thread" needs to poll the state of a collection of "worker threads" as they complete a set of tasks.  However, care should be exercised if other (unrelated) threads may also be running in the same module - in such cases, using THREAD STATUS is the preferred solution.  If polling is not desired, the WaitForMultipleObjects API function can also be useful - see THREAD CLOSE for more information.

Restrictions

THREADCOUNT includes threads that have had their thread handle released with THREAD CLOSE, yet are still running.

Threads are initialized and started asynchronously, so it is wise to give the operating system a small amount of time to perform thread initialization before using the THREADCOUNT function to monitor the thread.

A thread Function may not be directly called or executed, except by a THREAD CREATE statement.  This restriction is imposed to ensure that PowerBASIC run-time library can maintain a thread-safe state at all times, correctly allocate and deallocate internal thread-local storage), and functions such as THREADCOUNT can return accurate values.  See THREAD CREATE for more information and solutions.

See also

FUNCTION/END FUNCTION, THREAD CLOSE, THREAD Code Group, THREAD CREATE, THREAD Object, THREAD RESUME, THREAD STATUS, THREAD SUSPEND, THREADED, THREADID

Example

FUNCTION tZ(BYVAL x&) AS LONG

  ' Wait for a random time

  SLEEP x& * RND(1,1000)

  FUNCTION = 1

END FUNCTION

 

FUNCTION PBMAIN

  ' Create 10 threads

  FOR x& = 1 TO 10

    THREAD CREATE tZ(x&) TO hThread???

    THREAD CLOSE hThread??? TO lResult&

  NEXT x&

 

  'Wait until the threads are all done

  DO

    SLEEP 100

  LOOP WHILE THREADCOUNT > 1

END FUNCTION