'
' Example taken from https://computing.llnl.gov/tutorials/pthreads/#CreatingThreads
'
' Note that BaCon statements are not thread safe and therefore need a join or mutex!
'
' PvE 2010 - GPL.
'
'-------------------------------------------------------------------------------
INCLUDE "pthread.bac"
CONST NUM_THREADS = 5
DECLARE threads[NUM_THREADS]
' Use genuine PTHREAD types here
DECLARE mutex TYPE pthread_mutex_t
DECLARE attr TYPE pthread_attr_t
' Set thread attribute
pthread_attr_init(ADDRESS(attr))
pthread_attr_setdetachstate(ADDRESS(attr), PTHREAD_CREATE_JOINABLE)
' Initialize mutex
pthread_mutex_init(ADDRESS(mutex), 0)
'-------------------------------------------------------------------------------
SUB PrintHello(NUMBER threadid)
LOCAL mystacksize
pthread_mutex_lock(ADDRESS(mutex))
pthread_attr_getstacksize (ADDRESS(attr), ADDRESS(mystacksize))
PRINT "Hello World! It's me, thread #", threadid, " and this is my stacksize: ", mystacksize
pthread_mutex_unlock(ADDRESS(mutex))
pthread_exit(0)
END SUB
'-------------------------------------------------------------------------------
FOR t = 0 TO NUM_THREADS - 1
pthread_mutex_lock(ADDRESS(mutex))
PRINT "In main: creating thread ", t
pthread_mutex_unlock(ADDRESS(mutex))
rc = pthread_create(ADDRESS(threads[t]), ADDRESS(attr), PrintHello, t)
IF rc THEN
PRINT "ERROR: return code from pthread_create() is ", rc
END -1
END IF
NEXT
pthread_mutex_destroy(ADDRESS(mutex))
pthread_exit(0)