This commit is contained in:
Ingy döt Net 2013-04-10 16:57:12 -07:00
parent 518da4a923
commit 764da6cbbb
6144 changed files with 83610 additions and 11 deletions

View file

@ -0,0 +1 @@
Using either native language concurrency syntax or freely available libraries write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use [[thread|threads]], tasks, co-routines, or whatever concurrency is called in your language.

View file

@ -0,0 +1,4 @@
---
category:
- Basic language learning
note: Concurrency

View file

@ -0,0 +1,9 @@
main:(
PROC echo = (STRING string)VOID:
printf(($gl$,string));
PAR(
echo("Enjoy"),
echo("Rosetta"),
echo("Code")
)
)

View file

@ -0,0 +1,17 @@
with Ada.Text_IO, Ada.Numerics.Float_Random;
procedure Concurrent_Hello is
type Messages is (Enjoy, Rosetta, Code);
task type Writer (Message : Messages);
task body Writer is
Seed : Ada.Numerics.Float_Random.Generator;
begin
Ada.Numerics.Float_Random.Reset (Seed); -- time-dependent, see ARM A.5.2
delay Duration (Ada.Numerics.Float_Random.Random (Seed));
Ada.Text_IO.Put_Line (Messages'Image(Message));
end Writer;
Taks: array(Messages) of access Writer -- 3 Writer tasks will immediately run
:= (new Writer(Enjoy), new Writer(Rosetta), new Writer(Code));
begin
null; -- the "environment task" doesn't need to do anything
end Concurrent_Hello;

View file

@ -0,0 +1,31 @@
INSTALL @lib$+"TIMERLIB"
tID1% = FN_ontimer(100, PROCtask1, 1)
tID2% = FN_ontimer(100, PROCtask2, 1)
tID3% = FN_ontimer(100, PROCtask3, 1)
ON ERROR PRINT REPORT$ : PROCcleanup : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask1
PRINT "Enjoy"
ENDPROC
DEF PROCtask2
PRINT "Rosetta"
ENDPROC
DEF PROCtask3
PRINT "Code"
ENDPROC
DEF PROCcleanup
PROC_killtimer(tID1%)
PROC_killtimer(tID2%)
PROC_killtimer(tID3%)
ENDPROC

View file

@ -0,0 +1,20 @@
#include <iostream>
#include <ppl.h> // MSVC++
void a(void) { std::cout << "Eat\n"; }
void b(void) { std::cout << "At\n"; }
void c(void) { std::cout << "Joe's\n"; }
int main()
{
// function pointers
Concurrency::parallel_invoke(&a, &b, &c);
// C++11 lambda functions
Concurrency::parallel_invoke(
[]{ std::cout << "Enjoy\n"; },
[]{ std::cout << "Rosetta\n"; },
[]{ std::cout << "Code\n"; }
);
return 0;
}

View file

@ -0,0 +1,56 @@
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t condm = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int bang = 0;
#define WAITBANG() do { \
pthread_mutex_lock(&condm); \
while( bang == 0 ) \
{ \
pthread_cond_wait(&cond, &condm); \
} \
pthread_mutex_unlock(&condm); } while(0);\
void *t_enjoy(void *p)
{
WAITBANG();
printf("Enjoy\n");
pthread_exit(0);
}
void *t_rosetta(void *p)
{
WAITBANG();
printf("Rosetta\n");
pthread_exit(0);
}
void *t_code(void *p)
{
WAITBANG();
printf("Code\n");
pthread_exit(0);
}
typedef void *(*threadfunc)(void *);
int main()
{
int i;
pthread_t a[3];
threadfunc p[3] = {t_enjoy, t_rosetta, t_code};
for(i=0;i<3;i++)
{
pthread_create(&a[i], NULL, p[i], NULL);
}
sleep(1);
bang = 1;
pthread_cond_broadcast(&cond);
for(i=0;i<3;i++)
{
pthread_join(a[i], NULL);
}
}

View file

@ -0,0 +1,11 @@
#include <stdio.h>
#include <omp.h>
int main()
{
const char *str[] = { "Enjoy", "Rosetta", "Code" };
#pragma omp parallel for num_threads(3)
for (int i = 0; i < 3; i++)
printf("%s\n", str[i]);
return 0;
}

View file

@ -0,0 +1,2 @@
(doseq [text ["Enjoy" "Rosetta" "Code"]]
(future (println text)))

View file

@ -0,0 +1,5 @@
exec = require('child_process').exec
for word in ["Enjoy", "Rosetta", "Code"]
exec "echo #{word}", (err, stdout) ->
console.log stdout

View file

@ -0,0 +1,10 @@
(defun concurrency-example (&optional (out *standard-output*))
(let ((lock (bordeaux-threads:make-lock)))
(flet ((writer (string)
#'(lambda ()
(bordeaux-threads:acquire-lock lock t)
(write-line string out)
(bordeaux-threads:release-lock lock))))
(bordeaux-threads:make-thread (writer "Enjoy"))
(bordeaux-threads:make-thread (writer "Rosetta"))
(bordeaux-threads:make-thread (writer "Code")))))

View file

@ -0,0 +1,8 @@
import std.stdio, std.random, std.parallelism, core.thread, core.time;
void main() {
foreach (s; ["Enjoy", "Rosetta", "Code"].parallel(1)) {
Thread.sleep(uniform(0, 1000).dur!"msecs");
s.writeln;
}
}

View file

@ -0,0 +1,9 @@
import tango.core.Thread;
import tango.io.Console;
import tango.math.Random;
void main() {
(new Thread( { Thread.sleep(Random.shared.next(1000) / 1000.0); Cout("Enjoy").newline; } )).start;
(new Thread( { Thread.sleep(Random.shared.next(1000) / 1000.0); Cout("Rosetta").newline; } )).start;
(new Thread( { Thread.sleep(Random.shared.next(1000) / 1000.0); Cout("Code").newline; } )).start;
}

View file

@ -0,0 +1,39 @@
program ConcurrentComputing;
{$APPTYPE CONSOLE}
uses SysUtils, Classes, Windows;
type
TRandomThread = class(TThread)
private
FString: string;
protected
procedure Execute; override;
public
constructor Create(const aString: string); overload;
end;
constructor TRandomThread.Create(const aString: string);
begin
inherited Create(False);
FreeOnTerminate := True;
FString := aString;
end;
procedure TRandomThread.Execute;
begin
Sleep(Random(5) * 100);
Writeln(FString);
end;
var
lThreadArray: Array[0..2] of THandle;
begin
Randomize;
lThreadArray[0] := TRandomThread.Create('Enjoy').Handle;
lThreadArray[1] := TRandomThread.Create('Rosetta').Handle;
lThreadArray[2] := TRandomThread.Create('Stone').Handle;
WaitForMultipleObjects(Length(lThreadArray), @lThreadArray, True, INFINITE);
end.

View file

@ -0,0 +1,4 @@
def base := timer.now()
for string in ["Enjoy", "Rosetta", "Code"] {
timer <- whenPast(base + entropy.nextInt(1000), fn { println(string) })
}

View file

@ -0,0 +1,9 @@
def seedVat := <import:org.erights.e.elang.interp.seedVatAuthor>(<unsafe>)
for string in ["Enjoy", "Rosetta", "Code"] {
seedVat <- (`
fn string {
println(string)
currentVat <- orderlyShutdown("done")
}
`) <- get(0) <- (string)
}

View file

@ -0,0 +1,19 @@
-module(hw).
-export([start/0]).
start() ->
[ spawn(fun() -> say(self(), X) end) || X <- ['Enjoy', 'Rosetta', 'Code'] ],
wait(2),
ok.
say(Pid,Str) ->
io:fwrite("~s~n",[Str]),
Pid ! done.
wait(N) ->
receive
done -> case N of
0 -> 0;
_N -> wait(N-1)
end
end.

View file

@ -0,0 +1,2 @@
|erlc hw.erl
|erl -run hw start -run init stop -noshell

View file

@ -0,0 +1,17 @@
procedure echo(sequence s)
puts(1,s)
puts(1,'\n')
end procedure
atom task1,task2,task3
task1 = task_create(routine_id("echo"),{"Enjoy"})
task_schedule(task1,1)
task2 = task_create(routine_id("echo"),{"Rosetta"})
task_schedule(task2,1)
task3 = task_create(routine_id("echo"),{"Code"})
task_schedule(task3,1)
task_yield()

View file

@ -0,0 +1,17 @@
require tasker.fs
require random.fs
: task ( str len -- )
64 NewTask 2 swap pass
( str len -- )
10 0 do
100 random ms
pause 2dup cr type
loop 2drop ;
: main
s" Enjoy" task
s" Rosetta" task
s" Code" task
begin pause single-tasking? until ;
main

View file

@ -0,0 +1,44 @@
program concurrency
implicit none
character(len=*), parameter :: str1 = 'Enjoy'
character(len=*), parameter :: str2 = 'Rosetta'
character(len=*), parameter :: str3 = 'Code'
integer :: i
real :: h
real, parameter :: one_third = 1.0e0/3
real, parameter :: two_thirds = 2.0e0/3
interface
integer function omp_get_thread_num
end function omp_get_thread_num
end interface
interface
integer function omp_get_num_threads
end function omp_get_num_threads
end interface
! Use OpenMP to create a team of threads
!$omp parallel do private(i,h)
do i=1,20
! First time through the master thread output the number of threads
! in the team
if (omp_get_thread_num() == 0 .and. i == 1) then
write(*,'(a,i0,a)') 'Using ',omp_get_num_threads(),' threads'
end if
! Randomize the order
call random_number(h)
!$omp critical
if (h < one_third) then
write(*,'(a)') str1
else if (h < two_thirds) then
write(*,'(a)') str2
else
write(*,'(a)') str3
end if
!$omp end critical
end do
!$omp end parallel do
end program concurrency

View file

@ -0,0 +1,22 @@
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
words := []string{"Enjoy", "Rosetta", "Code"}
rand.Seed(time.Now().UnixNano())
q := make(chan string)
for _, w := range words {
go func(w string) {
time.Sleep(time.Duration(rand.Int63n(1e9)))
q <- w
}(w)
}
for i := 0; i < len(words); i++ {
fmt.Println(<-q)
}
}

View file

@ -0,0 +1,25 @@
package main
import (
"log"
"math/rand"
"os"
"sync"
"time"
)
func main() {
words := []string{"Enjoy", "Rosetta", "Code"}
rand.Seed(time.Now().UnixNano())
l := log.New(os.Stdout, "", 0)
var q sync.WaitGroup
q.Add(len(words))
for _, w := range words {
w := w
time.AfterFunc(time.Duration(rand.Int63n(1e9)), func() {
l.Println(w)
q.Done()
})
}
q.Wait()
}

View file

@ -0,0 +1,25 @@
package main
import "fmt"
func main() {
w1 := make(chan bool, 1)
w2 := make(chan bool, 1)
w3 := make(chan bool, 1)
for i := 0; i < 3; i++ {
w1 <- true
w2 <- true
w3 <- true
fmt.Println()
for i := 0; i < 3; i++ {
select {
case <-w1:
fmt.Println("Enjoy")
case <-w2:
fmt.Println("Rosetta")
case <-w3:
fmt.Println("Code")
}
}
}
}

View file

@ -0,0 +1,6 @@
import Control.Concurrent
main = mapM_ forkIO [process1, process2, process3] where
process1 = putStrLn "Enjoy"
process2 = putStrLn "Rosetta"
process3 = putStrLn "Code"

View file

@ -0,0 +1,19 @@
import Control.Concurrent
import System.Random
concurrent :: IO ()
concurrent = do
var <- newMVar [] -- use an MVar to collect the results of each thread
mapM_ (forkIO . task var) ["Enjoy", "Rosetta", "Code"] -- run 3 threads
putStrLn "Press Return to show the results." -- while we wait for the user,
-- the threads run
_ <- getLine
takeMVar var >>= mapM_ putStrLn -- read the results and show them on screen
where
-- "task" is a thread
task v s = do
randomRIO (1,10) >>= \r -> threadDelay (r * 100000) -- wait a while
val <- takeMVar v -- read the MVar and block other threads from reading it
-- until we write another value to it
putMVar v (s : val) -- append a text string to the MVar and block other
-- threads from writing to it unless it is read first

View file

@ -0,0 +1,4 @@
procedure main()
L:=[ thread write("Enjoy"), thread write("Rosetta"), thread write("Code") ]
every wait(!L)
end

View file

@ -0,0 +1,33 @@
import java.util.concurrent.CyclicBarrier;
public class Threads
{
public static class DelayedMessagePrinter implements Runnable
{
private CyclicBarrier barrier;
private String msg;
public DelayedMessagePrinter(CyclicBarrier barrier, String msg)
{
this.barrier = barrier;
this.msg = msg;
}
public void run()
{
try
{ barrier.await(); }
catch (Exception e)
{ }
System.out.println(msg);
}
}
public static void main(String[] args)
{
CyclicBarrier barrier = new CyclicBarrier(3);
new Thread(new DelayedMessagePrinter(barrier, "Enjoy")).start();
new Thread(new DelayedMessagePrinter(barrier, "Rosetta")).start();
new Thread(new DelayedMessagePrinter(barrier, "Code")).start();
}
}

View file

@ -0,0 +1,4 @@
self.addEventListener('message', function (event) {
self.postMessage(event.data);
self.close();
}, false);

View file

@ -0,0 +1,10 @@
var words = ["Enjoy", "Rosetta", "Code"];
var workers = [];
for (var i = 0; i < words.length; i++) {
workers[i] = new Worker("concurrent_worker.js");
workers[i].addEventListener('message', function (event) {
console.log(event.data);
}, false);
workers[i].postMessage(words[i]);
}

View file

@ -0,0 +1,16 @@
co = {}
co[1] = coroutine.create( function() print "Enjoy" end )
co[2] = coroutine.create( function() print "Rosetta" end )
co[3] = coroutine.create( function() print "Code" end )
math.randomseed( os.time() )
h = {}
i = 0
repeat
j = math.random(3)
if h[j] == nil then
coroutine.resume( co[j] )
h[j] = true
i = i + 1
end
until i == 3

View file

@ -0,0 +1,9 @@
use threads;
use Time::HiRes qw(sleep);
$_->join for map {
threads->create(sub {
sleep rand;
print shift, "\n";
}, $_)
} qw(Enjoy Rosetta Code);

View file

@ -0,0 +1,10 @@
use feature qw( say );
use Coro;
use Coro::Timer qw( sleep );
$_->join for map {
async {
sleep rand;
say @_;
} $_
} qw( Enjoy Rosetta Code );

View file

@ -0,0 +1,5 @@
(for (N . Str) '("Enjoy" "Rosetta" "Code")
(task (- N) (rand 1000 4000) # Random start time 1 .. 4 sec
Str Str # Closure with string value
(println Str) # Task body: Print the string
(task @) ) ) # and stop the task

View file

@ -0,0 +1,6 @@
(for Str '("Enjoy" "Rosetta" "Code")
(let N (rand 1000 4000) # Randomize
(unless (fork) # Create child process
(wait N) # Wait 1 .. 4 sec
(println Str) # Print string
(bye) ) ) ) # Terminate child process

View file

@ -0,0 +1,10 @@
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> from concurrent import futures
>>> with futures.ProcessPoolExecutor() as executor:
... _ = list(executor.map(print, 'Enjoy Rosetta Code'.split()))
...
Enjoy
Rosetta
Code
>>>

View file

@ -0,0 +1,9 @@
import threading
import random
def echo(text):
print(text)
threading.Timer(random.random(), echo, ("Enjoy",)).start()
threading.Timer(random.random(), echo, ("Rosetta",)).start()
threading.Timer(random.random(), echo, ("Code",)).start()

View file

@ -0,0 +1,8 @@
import threading
import random
def echo(text):
print(text)
for text in ["Enjoy", "Rosetta", "Code"]:
threading.Timer(random.random(), echo, (text,)).start()

View file

@ -0,0 +1,14 @@
import random, sys, time
import threading
lock = threading.Lock()
def echo(s):
time.sleep(1e-2*random.random())
# use `.write()` with lock due to `print` prints empty lines occasionally
with lock:
sys.stdout.write(s)
sys.stdout.write('\n')
for line in 'Enjoy Rosetta Code'.split():
threading.Thread(target=echo, args=(line,)).start()

View file

@ -0,0 +1,9 @@
from __future__ import print_function
from multiprocessing import Pool
def main():
p = Pool()
p.map(print, 'Enjoy Rosetta Code'.split())
if __name__=="__main__":
main()

View file

@ -0,0 +1,9 @@
import random
from twisted.internet import reactor, task, defer
from twisted.python.util import println
delay = lambda: 1e-4*random.random()
d = defer.DeferredList([task.deferLater(reactor, delay(), println, line)
for line in 'Enjoy Rosetta Code'.split()])
d.addBoth(lambda _: reactor.stop())
reactor.run()

View file

@ -0,0 +1,7 @@
from __future__ import print_function
import random
import gevent
delay = lambda: 1e-4*random.random()
gevent.joinall([gevent.spawn_later(delay(), print, line)
for line in 'Enjoy Rosetta Code'.split()])

View file

@ -0,0 +1,4 @@
#lang racket
(for ([str '("Enjoy" "Rosetta" "Code")])
(thread (λ () (displayln str))))

View file

@ -0,0 +1,8 @@
%w{Enjoy Rosetta Code}.map do |x|
Thread.new do
sleep rand
puts x
end
end.each do |t|
t.join
end

View file

@ -0,0 +1,7 @@
import scala.actors.Futures
List("Enjoy", "Rosetta", "Code").map { x =>
Futures.future {
Thread.sleep((Math.random * 1000).toInt)
println(x)
}
}.foreach(_())

View file

@ -0,0 +1,3 @@
(parallel-execute (lambda () (print "Enjoy"))
(lambda () (print "Rosetta"))
(lambda () (print "Code")))

View file

@ -0,0 +1,3 @@
after [expr int(1000*rand())] {puts "Enjoy"}
after [expr int(1000*rand())] {puts "Rosetta"}
after [expr int(1000*rand())] {puts "Code"}

View file

@ -0,0 +1,3 @@
after idle {puts "Enjoy"}
after idle {puts "Rosetta"}
after idle {puts "Code"}

View file

@ -0,0 +1,13 @@
package require Thread
set pool [tpool::create -initcmd {
proc delayPrint msg {
after [expr int(1000*rand())]
puts $msg
}
}]
tpool::post -detached $pool [list delayPrint "Enjoy"]
tpool::post -detached $pool [list delayPrint "Rosetta"]
tpool::post -detached $pool [list delayPrint "Code"]
tpool::release $pool
after 1200 ;# Give threads time to do their work
exit