Jump to content

Synchronous concurrency: Difference between revisions

(Added C++ solution)
Line 1,648:
Concurrent units are established by use of the feed operator, which works much like an in-process object pipe. Since the final feed goes to a variable declaration that belongs to the outer thread, it serves as a backchannel from the printer thread. In this case the outer thread signals the desire for a line count by terminating the pipe to the printing thread.
(Note: soon these will be implemented with real threads in Perl 6, but this is currently emulated with coroutine semantics, aka lazy lists.)
 
=={{header|Phix}}==
Busy wait version (using threads).
This program is included in the distribution as demo\rosetta\Synchronous_concurrency.exw, which also contains single step-lock and queue-less versions of this code.
<lang Phix>atom frThread, -- file reader thread
lcThread -- line counter thread
 
sequence queue = {}
integer qlock = init_cs()
 
integer linecount = 1
 
procedure readfile()
object line
integer fn = open(command_line()[2],"r")
while 1 do
line = gets(fn)
enter_cs(qlock)
queue = append(queue,line)
leave_cs(qlock)
if atom(line) then exit end if
end while
close(fn)
wait_thread(lcThread)
printf(1,"Lines read: %d\n",linecount)
exit_thread(0)
end procedure
 
procedure countlines()
object line
linecount = 0
while 1 do
enter_cs(qlock)
if length(queue)=0 then
leave_cs(qlock)
-- sleep(0.1)
else
line = queue[1]
queue = queue[2..$]
leave_cs(qlock)
if atom(line) then exit end if
-- ?line
linecount += 1
end if
end while
exit_thread(0)
end procedure
 
frThread = create_thread(routine_id("readfile"),{})
lcThread = create_thread(routine_id("countlines"),{})
 
wait_thread(frThread)
puts(1,"done")
{} = wait_key()</lang>
 
=={{header|PicoLisp}}==
Line 1,698 ⟶ 1,752:
(inc 'Cnt) ) # Increment count
(yield Cnt 'unit1) ) ) # Send count to 'unit1'</lang>
 
=={{header|PureBasic}}==
PureBasic uses Semaphores and Mutex's to coordinate threads.
7,813

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.