Files
harbour-core/tests/mt/mttest07.prg
Viktor Szakats 58faf91453 2016-01-14 19:17 UTC+0100 Viktor Szakats (vszakats users.noreply.github.com)
* *
    % remove brandings and homepage [1] from copyright header. Pass 1 - using script.
      [1] nobody has access to it anymore AFAIK - and it's also just
          a redirect since long
    ! update url in copyright header
    ; this should make the diff between 3.4 and 3.2 easier to manage
2016-01-14 19:18:17 +01:00

89 lines
1.9 KiB
Plaintext

/*
* demonstration/test code for using mutexes to send/receive
* messages between threads to synchronize divided jobs between
* threads.
*
* Copyright 2008 Przemyslaw Czerpak <druzus / at / priv.onet.pl>
*
*/
#define N_THREADS 5
#define N_JOBS 10000
static s_aCounters
static s_mtxJobs
static s_mtxResults
proc main()
local aThreads, aResults, i, nDigit, nSum, nExpected
? Version()
? "Main start"
s_aCounters := array( N_THREADS )
aFill( s_aCounters, 0 )
aThreads := {}
aResults := {}
s_mtxJobs := hb_mutexCreate()
s_mtxResults := hb_mutexCreate()
? "Starting threads: "
for i := 1 to N_THREADS
aadd( aThreads, hb_threadStart( @thFunc() ) )
?? "<" + hb_ntos( i ) + ">"
next
? "Sending jobs... "
nDigit := 10
for i := 1 to N_JOBS
hb_mutexNotify( s_mtxJobs, nDigit )
//?? "<" + hb_ntos( i ) + ">"
nDigit++
next
? "Sending terminate values..."
for i := 1 to N_THREADS
hb_mutexNotify( s_mtxJobs, NIL )
?? "<" + hb_ntos( i ) + ">"
next
? "Collecting results... "
for i := 1 to N_JOBS
hb_mutexSubscribe( s_mtxResults,, @nDigit )
//?? "<" + hb_ntos( i ) + ">"
aadd( aResults, nDigit )
next
? "Waiting for threads..."
aEval( aThreads, {| x | hb_threadJoin( x ) } )
? "Threads joined"
nSum := 0
for each nDigit in aResults
nSum += nDigit
next
nSum := round( nSum, 2 )
nExpected := round( ( 10 + 10 + N_JOBS - 1 ) / 2 / 3 * N_JOBS, 2 )
if round( nSum - nExpected, 2 ) == 0
? "OK, final sum:", hb_ntos( nSum )
else
? "ERROR, final sum:", hb_ntos( nSum ), ;
"expected:", hb_ntos( nExpected )
endif
? "End of main"
return
proc thFunc()
local xJob, xResult
while .T.
hb_mutexSubscribe( s_mtxJobs,, @xJob )
if xJob == NIL
exit
endif
xResult := xJob / 3
hb_mutexNotify( s_mtxResults, xResult )
enddo
return