Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
5
Task/Concurrent-computing/00-META.yaml
Normal file
5
Task/Concurrent-computing/00-META.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
category:
|
||||
- Basic language learning
|
||||
from: http://rosettacode.org/wiki/Concurrent_computing
|
||||
note: Concurrency
|
||||
6
Task/Concurrent-computing/00-TASK.txt
Normal file
6
Task/Concurrent-computing/00-TASK.txt
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
;Task:
|
||||
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.
|
||||
<br><br>
|
||||
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
main:(
|
||||
PROC echo = (STRING string)VOID:
|
||||
printf(($gl$,string));
|
||||
PAR(
|
||||
echo("Enjoy"),
|
||||
echo("Rosetta"),
|
||||
echo("Code")
|
||||
)
|
||||
)
|
||||
1
Task/Concurrent-computing/APL/concurrent-computing.apl
Normal file
1
Task/Concurrent-computing/APL/concurrent-computing.apl
Normal file
|
|
@ -0,0 +1 @@
|
|||
{⎕←⍵}&¨'Enjoy' 'Rosetta' 'Code'
|
||||
17
Task/Concurrent-computing/Ada/concurrent-computing.ada
Normal file
17
Task/Concurrent-computing/Ada/concurrent-computing.ada
Normal 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;
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
let words = ["Enjoy", "Rosetta", "Code"]
|
||||
|
||||
for word in words:
|
||||
(word) |> async (w) =>
|
||||
sleep(random())
|
||||
print(w)
|
||||
|
|
@ -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
|
||||
18
Task/Concurrent-computing/BaCon/concurrent-computing.bacon
Normal file
18
Task/Concurrent-computing/BaCon/concurrent-computing.bacon
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
' Concurrent computing using the OpenMP extension in GCC. Requires BaCon 3.6 or higher.
|
||||
|
||||
' Specify compiler flag
|
||||
PRAGMA OPTIONS -fopenmp
|
||||
|
||||
' Sepcify linker flag
|
||||
PRAGMA LDFLAGS -lgomp
|
||||
|
||||
' Declare array with text
|
||||
DECLARE str$[] = { "Enjoy", "Rosetta", "Code" }
|
||||
|
||||
' Indicate MP optimization for FOR loop
|
||||
PRAGMA omp parallel for num_threads(3)
|
||||
|
||||
' The actual FOR loop
|
||||
FOR i = 0 TO 2
|
||||
PRINT str$[i]
|
||||
NEXT
|
||||
27
Task/Concurrent-computing/C++/concurrent-computing-1.cpp
Normal file
27
Task/Concurrent-computing/C++/concurrent-computing-1.cpp
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
#include <thread>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <random>
|
||||
#include <chrono>
|
||||
|
||||
int main()
|
||||
{
|
||||
std::random_device rd;
|
||||
std::mt19937 eng(rd()); // mt19937 generator with a hardware random seed.
|
||||
std::uniform_int_distribution<> dist(1,1000);
|
||||
std::vector<std::thread> threads;
|
||||
|
||||
for(const auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) {
|
||||
// between 1 and 1000ms per our distribution
|
||||
std::chrono::milliseconds duration(dist(eng));
|
||||
|
||||
threads.emplace_back([str, duration](){
|
||||
std::this_thread::sleep_for(duration);
|
||||
std::cout << str;
|
||||
});
|
||||
}
|
||||
|
||||
for(auto& t: threads) t.join();
|
||||
|
||||
return 0;
|
||||
}
|
||||
20
Task/Concurrent-computing/C++/concurrent-computing-2.cpp
Normal file
20
Task/Concurrent-computing/C++/concurrent-computing-2.cpp
Normal 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;
|
||||
}
|
||||
21
Task/Concurrent-computing/C-sharp/concurrent-computing-1.cs
Normal file
21
Task/Concurrent-computing/C-sharp/concurrent-computing-1.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
static Random tRand = new Random();
|
||||
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Thread t = new Thread(new ParameterizedThreadStart(WriteText));
|
||||
t.Start("Enjoy");
|
||||
|
||||
t = new Thread(new ParameterizedThreadStart(WriteText));
|
||||
t.Start("Rosetta");
|
||||
|
||||
t = new Thread(new ParameterizedThreadStart(WriteText));
|
||||
t.Start("Code");
|
||||
|
||||
Console.ReadLine();
|
||||
}
|
||||
|
||||
private static void WriteText(object p)
|
||||
{
|
||||
Thread.Sleep(tRand.Next(1000, 4000));
|
||||
Console.WriteLine(p);
|
||||
}
|
||||
13
Task/Concurrent-computing/C-sharp/concurrent-computing-2.cs
Normal file
13
Task/Concurrent-computing/C-sharp/concurrent-computing-2.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public class Program
|
||||
{
|
||||
static async Task Main() {
|
||||
Task t1 = Task.Run(() => Console.WriteLine("Enjoy"));
|
||||
Task t2 = Task.Run(() => Console.WriteLine("Rosetta"));
|
||||
Task t3 = Task.Run(() => Console.WriteLine("Code"));
|
||||
|
||||
await Task.WhenAll(t1, t2, t3);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public class Program
|
||||
{
|
||||
static void Main() => Parallel.ForEach(new[] {"Enjoy", "Rosetta", "Code"}, s => Console.WriteLine(s));
|
||||
}
|
||||
56
Task/Concurrent-computing/C/concurrent-computing-1.c
Normal file
56
Task/Concurrent-computing/C/concurrent-computing-1.c
Normal 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);
|
||||
}
|
||||
}
|
||||
11
Task/Concurrent-computing/C/concurrent-computing-2.c
Normal file
11
Task/Concurrent-computing/C/concurrent-computing-2.c
Normal 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;
|
||||
}
|
||||
5
Task/Concurrent-computing/Cind/concurrent-computing.cind
Normal file
5
Task/Concurrent-computing/Cind/concurrent-computing.cind
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
execute() {
|
||||
{# host.println("Enjoy");
|
||||
# host.println("Rosetta");
|
||||
# host.println("Code"); }
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(doseq [text ["Enjoy" "Rosetta" "Code"]]
|
||||
(future (println text)))
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
(require '[clojure.core.async :refer [go <! timeout]])
|
||||
(doseq [text ["Enjoy" "Rosetta" "Code"]]
|
||||
(go
|
||||
(<! (timeout (rand-int 1000))) ; wait a random fraction of a second,
|
||||
(println text)))
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
{ exec } = require 'child_process'
|
||||
|
||||
for word in [ 'Enjoy', 'Rosetta', 'Code' ]
|
||||
exec "echo #{word}", (err, stdout) ->
|
||||
console.log stdout
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
# The "master" file.
|
||||
|
||||
{ fork } = require 'child_process'
|
||||
path = require 'path'
|
||||
child_name = path.join __dirname, 'child.coffee'
|
||||
words = [ 'Enjoy', 'Rosetta', 'Code' ]
|
||||
|
||||
fork child_name, [ word ] for word in words
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
# child.coffee
|
||||
|
||||
console.log process.argv[ 2 ]
|
||||
|
|
@ -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")))))
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
require "channel"
|
||||
require "fiber"
|
||||
require "random"
|
||||
|
||||
done = Channel(Nil).new
|
||||
|
||||
"Enjoy Rosetta Code".split.map do |x|
|
||||
spawn do
|
||||
sleep Random.new.rand(0..500).milliseconds
|
||||
puts x
|
||||
done.send nil
|
||||
end
|
||||
end
|
||||
|
||||
3.times do
|
||||
done.receive
|
||||
end
|
||||
8
Task/Concurrent-computing/D/concurrent-computing-1.d
Normal file
8
Task/Concurrent-computing/D/concurrent-computing-1.d
Normal 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;
|
||||
}
|
||||
}
|
||||
9
Task/Concurrent-computing/D/concurrent-computing-2.d
Normal file
9
Task/Concurrent-computing/D/concurrent-computing-2.d
Normal 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;
|
||||
}
|
||||
16
Task/Concurrent-computing/Dart/concurrent-computing-1.dart
Normal file
16
Task/Concurrent-computing/Dart/concurrent-computing-1.dart
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import 'dart:math' show Random;
|
||||
|
||||
main(){
|
||||
enjoy() .then( (e) => print(e) );
|
||||
rosetta() .then( (r) => print(r) );
|
||||
code() .then( (c) => print(c) );
|
||||
}
|
||||
|
||||
// Create random number generator
|
||||
var rng = Random();
|
||||
|
||||
// Each function returns a future that starts after a delay
|
||||
// Like using setTimeout with a Promise in Javascript
|
||||
enjoy() => Future.delayed( Duration( milliseconds: rng.nextInt( 10 ) ), () => "Enjoy");
|
||||
rosetta() => Future.delayed( Duration( milliseconds: rng.nextInt( 10 ) ), () => "Rosetta");
|
||||
code() => Future.delayed( Duration( milliseconds: rng.nextInt( 10 ) ), () => "Code");
|
||||
59
Task/Concurrent-computing/Dart/concurrent-computing-2.dart
Normal file
59
Task/Concurrent-computing/Dart/concurrent-computing-2.dart
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import 'dart:isolate' show Isolate, ReceivePort;
|
||||
import 'dart:io' show exit, sleep;
|
||||
import 'dart:math' show Random;
|
||||
|
||||
main() {
|
||||
// Create ReceivePort to receive done messages
|
||||
// Called a channel in other languages
|
||||
var receiver = ReceivePort();
|
||||
|
||||
// Create job counter
|
||||
var job_count = 3;
|
||||
|
||||
// Create job pool
|
||||
var jobs = [ enjoy, rosetta, code ];
|
||||
|
||||
// Create random number generator
|
||||
var rng = Random();
|
||||
|
||||
for ( var job in jobs ) {
|
||||
// Sleep for random duration up to half a second
|
||||
var sleep_time = Duration( milliseconds: rng.nextInt( 500 ) );
|
||||
|
||||
// Spawn Isolate to do work
|
||||
// When finished the second argument will be sent to the receiver via the SendPort specified in onExit
|
||||
Isolate.spawn( job, sleep_time, onExit: receiver.sendPort );
|
||||
|
||||
}
|
||||
|
||||
// Do something in main isolate
|
||||
print("from main isolate\n");
|
||||
|
||||
// Register a listener on the ReceivePort, it gets called whenver something is sent on its SendPort
|
||||
// We'll ignore the message with _ because we don't care about the data, just the event
|
||||
receiver.listen( (_) {
|
||||
// Decrement job counter
|
||||
job_count -= 1;
|
||||
// If jobs are all finished
|
||||
if ( job_count == 0 ) {
|
||||
print("\nall jobs finished!");
|
||||
exit(0);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
enjoy ( duration ) {
|
||||
sleep( duration ) ;
|
||||
print("Enjoy");
|
||||
}
|
||||
|
||||
rosetta ( duration ) {
|
||||
sleep( duration );
|
||||
print("Rosetta");
|
||||
}
|
||||
|
||||
code ( duration ) {
|
||||
sleep( duration );
|
||||
print("Code");
|
||||
}
|
||||
39
Task/Concurrent-computing/Delphi/concurrent-computing.delphi
Normal file
39
Task/Concurrent-computing/Delphi/concurrent-computing.delphi
Normal 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.
|
||||
14
Task/Concurrent-computing/Dodo0/concurrent-computing.dodo0
Normal file
14
Task/Concurrent-computing/Dodo0/concurrent-computing.dodo0
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
fun parprint -> text, return
|
||||
(
|
||||
fork() -> return, throw
|
||||
println(text, return)
|
||||
| x
|
||||
return()
|
||||
)
|
||||
| parprint
|
||||
|
||||
parprint("Enjoy") ->
|
||||
parprint("Rosetta") ->
|
||||
parprint("Code") ->
|
||||
|
||||
exit()
|
||||
4
Task/Concurrent-computing/E/concurrent-computing-1.e
Normal file
4
Task/Concurrent-computing/E/concurrent-computing-1.e
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
def base := timer.now()
|
||||
for string in ["Enjoy", "Rosetta", "Code"] {
|
||||
timer <- whenPast(base + entropy.nextInt(1000), fn { println(string) })
|
||||
}
|
||||
9
Task/Concurrent-computing/E/concurrent-computing-2.e
Normal file
9
Task/Concurrent-computing/E/concurrent-computing-2.e
Normal 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)
|
||||
}
|
||||
13
Task/Concurrent-computing/EchoLisp/concurrent-computing.l
Normal file
13
Task/Concurrent-computing/EchoLisp/concurrent-computing.l
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
(lib 'tasks) ;; use the tasks library
|
||||
|
||||
(define (tprint line ) ;; task definition
|
||||
(writeln _TASK line)
|
||||
#f )
|
||||
|
||||
(for-each task-run ;; run three // tasks
|
||||
(map (curry make-task tprint) '(Enjoy Rosetta code )))
|
||||
|
||||
→
|
||||
#task:id:66:running Rosetta
|
||||
#task:id:67:running code
|
||||
#task:id:65:running Enjoy
|
||||
10
Task/Concurrent-computing/Egel/concurrent-computing.egel
Normal file
10
Task/Concurrent-computing/Egel/concurrent-computing.egel
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import "prelude.eg"
|
||||
import "io.ego"
|
||||
|
||||
using System
|
||||
using IO
|
||||
|
||||
def main =
|
||||
let _ = par (par [_ -> print "enjoy\n"]
|
||||
[_ -> print "rosetta\n"])
|
||||
[_ -> print "code\n"] in nop
|
||||
13
Task/Concurrent-computing/Elixir/concurrent-computing.elixir
Normal file
13
Task/Concurrent-computing/Elixir/concurrent-computing.elixir
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
defmodule Concurrent do
|
||||
def computing(xs) do
|
||||
Enum.each(xs, fn x ->
|
||||
spawn(fn ->
|
||||
Process.sleep(:rand.uniform(1000))
|
||||
IO.puts x
|
||||
end)
|
||||
end)
|
||||
Process.sleep(1000)
|
||||
end
|
||||
end
|
||||
|
||||
Concurrent.computing ["Enjoy", "Rosetta", "Code"]
|
||||
19
Task/Concurrent-computing/Erlang/concurrent-computing-1.erl
Normal file
19
Task/Concurrent-computing/Erlang/concurrent-computing-1.erl
Normal 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.
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
|erlc hw.erl
|
||||
|erl -run hw start -run init stop -noshell
|
||||
|
|
@ -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()
|
||||
12
Task/Concurrent-computing/F-Sharp/concurrent-computing.fs
Normal file
12
Task/Concurrent-computing/F-Sharp/concurrent-computing.fs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
module Seq =
|
||||
let piter f xs =
|
||||
seq { for x in xs -> async { f x } }
|
||||
|> Async.Parallel
|
||||
|> Async.RunSynchronously
|
||||
|> ignore
|
||||
|
||||
let main() = Seq.piter
|
||||
(System.Console.WriteLine:string->unit)
|
||||
["Enjoy"; "Rosetta"; "Code";]
|
||||
|
||||
main()
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
USE: concurrency.combinators
|
||||
|
||||
{ "Enjoy" "Rosetta" "Code" } [ print ] parallel-each
|
||||
17
Task/Concurrent-computing/Forth/concurrent-computing.fth
Normal file
17
Task/Concurrent-computing/Forth/concurrent-computing.fth
Normal 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
|
||||
44
Task/Concurrent-computing/Fortran/concurrent-computing.f
Normal file
44
Task/Concurrent-computing/Fortran/concurrent-computing.f
Normal 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
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
' FB 1.05.0 Win64
|
||||
' Compiled with -mt switch (to use threadsafe runtiume)
|
||||
' The 'ThreadCall' functionality in FB is based internally on LibFFi (see [https://github.com/libffi/libffi/blob/master/LICENSE] for license)
|
||||
|
||||
Sub thread1()
|
||||
Print "Enjoy"
|
||||
End Sub
|
||||
|
||||
Sub thread2()
|
||||
Print "Rosetta"
|
||||
End Sub
|
||||
|
||||
Sub thread3()
|
||||
Print "Code"
|
||||
End Sub
|
||||
|
||||
Print "Press any key to print next batch of 3 strings or ESC to quit"
|
||||
Print
|
||||
|
||||
Do
|
||||
Dim t1 As Any Ptr = ThreadCall thread1
|
||||
Dim t2 As Any Ptr = ThreadCall thread2
|
||||
Dim t3 As Any Ptr = ThreadCall thread3
|
||||
ThreadWait t1
|
||||
ThreadWait t2
|
||||
ThreadWait t3
|
||||
Print
|
||||
Sleep
|
||||
Loop While Inkey <> Chr(27)
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
include "NSLog.incl"
|
||||
|
||||
long priority(2)
|
||||
priority(0) = _dispatchPriorityDefault
|
||||
priority(1) = _dispatchPriorityHigh
|
||||
priority(2) = _dispatchPriorityLow
|
||||
|
||||
dispatchglobal , priority(rnd(3)-1)
|
||||
NSLog(@"Enjoy")
|
||||
dispatchend
|
||||
|
||||
dispatchglobal , priority(rnd(3)-1)
|
||||
NSLog(@"Rosetta")
|
||||
dispatchend
|
||||
|
||||
dispatchglobal , priority(rnd(3)-1)
|
||||
NSLog(@"Code")
|
||||
dispatchend
|
||||
|
||||
HandleEvents
|
||||
23
Task/Concurrent-computing/Go/concurrent-computing-1.go
Normal file
23
Task/Concurrent-computing/Go/concurrent-computing-1.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang.org/x/exp/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
words := []string{"Enjoy", "Rosetta", "Code"}
|
||||
seed := uint64(time.Now().UnixNano())
|
||||
q := make(chan string)
|
||||
for i, w := range words {
|
||||
go func(w string, seed uint64) {
|
||||
r := rand.New(rand.NewSource(seed))
|
||||
time.Sleep(time.Duration(r.Int63n(1e9)))
|
||||
q <- w
|
||||
}(w, seed+uint64(i))
|
||||
}
|
||||
for i := 0; i < len(words); i++ {
|
||||
fmt.Println(<-q)
|
||||
}
|
||||
}
|
||||
25
Task/Concurrent-computing/Go/concurrent-computing-2.go
Normal file
25
Task/Concurrent-computing/Go/concurrent-computing-2.go
Normal 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()
|
||||
}
|
||||
25
Task/Concurrent-computing/Go/concurrent-computing-3.go
Normal file
25
Task/Concurrent-computing/Go/concurrent-computing-3.go
Normal 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
'Enjoy Rosetta Code'.tokenize().collect { w ->
|
||||
Thread.start {
|
||||
Thread.sleep(1000 * Math.random() as int)
|
||||
println w
|
||||
}
|
||||
}.each { it.join() }
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import Control.Concurrent
|
||||
|
||||
main = mapM_ forkIO [process1, process2, process3] where
|
||||
process1 = putStrLn "Enjoy"
|
||||
process2 = putStrLn "Rosetta"
|
||||
process3 = putStrLn "Code"
|
||||
19
Task/Concurrent-computing/Haskell/concurrent-computing-2.hs
Normal file
19
Task/Concurrent-computing/Haskell/concurrent-computing-2.hs
Normal 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
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
procedure main()
|
||||
L:=[ thread write("Enjoy"), thread write("Rosetta"), thread write("Code") ]
|
||||
every wait(!L)
|
||||
end
|
||||
18
Task/Concurrent-computing/J/concurrent-computing-1.j
Normal file
18
Task/Concurrent-computing/J/concurrent-computing-1.j
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
reqthreads=: {{ 0&T.@''^:(0>.y-1 T.'')0 }}
|
||||
dispatchwith=: (t.'')every
|
||||
newmutex=: 10&T.
|
||||
lock=: 11&T.
|
||||
unlock=: 13&T.
|
||||
synced=: {{
|
||||
lock n
|
||||
r=. u y
|
||||
unlock n
|
||||
r
|
||||
}}
|
||||
register=: {{ out=: out, y }} synced (newmutex 0)
|
||||
task=: {{
|
||||
reqthreads 3 NB. at least 3 worker threads
|
||||
out=: EMPTY
|
||||
#@> register dispatchwith ;:'Enjoy Rosetta Code'
|
||||
out
|
||||
}}
|
||||
8
Task/Concurrent-computing/J/concurrent-computing-2.j
Normal file
8
Task/Concurrent-computing/J/concurrent-computing-2.j
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
task''
|
||||
Enjoy
|
||||
Rosetta
|
||||
Code
|
||||
task''
|
||||
Enjoy
|
||||
Code
|
||||
Rosetta
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
Thread[] threads = new Thread[3];
|
||||
threads[0] = new Thread(() -> System.out.println("enjoy"));
|
||||
threads[1] = new Thread(() -> System.out.println("rosetta"));
|
||||
threads[2] = new Thread(() -> System.out.println("code"));
|
||||
Collections.shuffle(Arrays.asList(threads));
|
||||
for (Thread thread : threads)
|
||||
thread.start();
|
||||
33
Task/Concurrent-computing/Java/concurrent-computing-2.java
Normal file
33
Task/Concurrent-computing/Java/concurrent-computing-2.java
Normal 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
self.addEventListener('message', function (event) {
|
||||
self.postMessage(event.data);
|
||||
self.close();
|
||||
}, false);
|
||||
|
|
@ -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]);
|
||||
}
|
||||
10
Task/Concurrent-computing/Julia/concurrent-computing.julia
Normal file
10
Task/Concurrent-computing/Julia/concurrent-computing.julia
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
words = ["Enjoy", "Rosetta", "Code"]
|
||||
|
||||
function sleepprint(s)
|
||||
sleep(rand())
|
||||
println(s)
|
||||
end
|
||||
|
||||
@sync for word in words
|
||||
@async sleepprint(word)
|
||||
end
|
||||
16
Task/Concurrent-computing/Kotlin/concurrent-computing.kotlin
Normal file
16
Task/Concurrent-computing/Kotlin/concurrent-computing.kotlin
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
// version 1.1.2
|
||||
|
||||
import java.util.concurrent.CyclicBarrier
|
||||
|
||||
class DelayedMessagePrinter(val barrier: CyclicBarrier, val msg: String) : Runnable {
|
||||
override fun run() {
|
||||
barrier.await()
|
||||
println(msg)
|
||||
}
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val msgs = listOf("Enjoy", "Rosetta", "Code")
|
||||
val barrier = CyclicBarrier(msgs.size)
|
||||
for (msg in msgs) Thread(DelayedMessagePrinter(barrier, msg)).start()
|
||||
}
|
||||
26
Task/Concurrent-computing/LFE/concurrent-computing.lfe
Normal file
26
Task/Concurrent-computing/LFE/concurrent-computing.lfe
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
;;;
|
||||
;;; This is a straight port of the Erlang version.
|
||||
;;;
|
||||
;;; You can run this under the LFE REPL as follows:
|
||||
;;;
|
||||
;;; (slurp "concurrent-computing.lfe")
|
||||
;;; (start)
|
||||
;;;
|
||||
(defmodule concurrent-computing
|
||||
(export (start 0)))
|
||||
|
||||
(defun start ()
|
||||
(lc ((<- word '("Enjoy" "Rosetta" "Code")))
|
||||
(spawn (lambda () (say (self) word))))
|
||||
(wait 2)
|
||||
'ok)
|
||||
|
||||
(defun say (pid word)
|
||||
(lfe_io:format "~p~n" (list word))
|
||||
(! pid 'done))
|
||||
|
||||
(defun wait (n)
|
||||
(receive
|
||||
('done (case n
|
||||
(0 0)
|
||||
(_n (wait (- n 1)))))))
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
:- object(concurrency).
|
||||
|
||||
:- initialization(output).
|
||||
|
||||
output :-
|
||||
threaded((
|
||||
write('Enjoy'),
|
||||
write('Rosetta'),
|
||||
write('Code')
|
||||
)).
|
||||
|
||||
:- end_object.
|
||||
16
Task/Concurrent-computing/Lua/concurrent-computing.lua
Normal file
16
Task/Concurrent-computing/Lua/concurrent-computing.lua
Normal 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
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
Thread.Plan Concurrent
|
||||
Module CheckIt {
|
||||
Flush \\ empty stack of values
|
||||
Data "Enjoy", "Rosetta", "Code"
|
||||
For i=1 to 3 {
|
||||
Thread {
|
||||
Print A$
|
||||
Thread This Erase
|
||||
} As K
|
||||
Read M$
|
||||
Thread K Execute Static A$=M$
|
||||
Thread K Interval Random(500,1000)
|
||||
Threads
|
||||
}
|
||||
Rem : Wait 3000 ' we can use just a wait loop, or the main.task loop
|
||||
\\ main.task exit if all threads erased
|
||||
Main.Task 30 {
|
||||
}
|
||||
\\ when module exit all threads from this module get a signal to stop.
|
||||
\\ we can use Threads Erase to erase all threads.
|
||||
\\ Also if we press Esc we do the same
|
||||
}
|
||||
CheckIt
|
||||
|
||||
\\ we can define again the module, and now we get three time each name, but not every time three same names.
|
||||
\\ if we change to Threads.Plan Sequential we get always the three same names
|
||||
\\ Also in concurrent plan we can use a block to ensure that statements run without other thread executed in parallel.
|
||||
|
||||
Module CheckIt {
|
||||
Flush \\ empty stack of values
|
||||
Data "Enjoy", "Rosetta", "Code"
|
||||
For i=1 to 3 {
|
||||
Thread {
|
||||
Print A$
|
||||
Print A$
|
||||
Print A$
|
||||
Thread This Erase
|
||||
} As K
|
||||
Read M$
|
||||
Thread K Execute Static A$=M$
|
||||
Thread K Interval Random(500,530)
|
||||
Threads
|
||||
}
|
||||
Rem : Wait 3000 ' we can use just a wait loop, or the main.task loop
|
||||
\\ main.task exit if all threads erased
|
||||
Main.Task 30 {
|
||||
}
|
||||
\\ when module exit all threads from this module get a signal to stop.
|
||||
\\ we can use Threads Erase to erase all threads.
|
||||
\\ Also if we press Esc we do the same
|
||||
}
|
||||
CheckIt
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
ParallelDo[
|
||||
Pause[RandomReal[]];
|
||||
Print[s],
|
||||
{s, {"Enjoy", "Rosetta", "Code"}}
|
||||
]
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
:- module concurrent_computing.
|
||||
:- interface.
|
||||
|
||||
:- import_module io.
|
||||
:- pred main(io::di, io::uo) is cc_multi.
|
||||
|
||||
:- implementation.
|
||||
:- import_module thread.
|
||||
|
||||
main(!IO) :-
|
||||
spawn(io.print_cc("Enjoy\n"), !IO),
|
||||
spawn(io.print_cc("Rosetta\n"), !IO),
|
||||
spawn(io.print_cc("Code\n"), !IO).
|
||||
34
Task/Concurrent-computing/Neko/concurrent-computing.neko
Normal file
34
Task/Concurrent-computing/Neko/concurrent-computing.neko
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
Concurrent computing, in Neko
|
||||
*/
|
||||
|
||||
var thread_create = $loader.loadprim("std@thread_create", 2);
|
||||
|
||||
var subtask = function(message) {
|
||||
$print(message, "\n");
|
||||
}
|
||||
|
||||
/* The thread functions happen so fast as to look sequential */
|
||||
thread_create(subtask, "Enjoy");
|
||||
thread_create(subtask, "Rosetta");
|
||||
thread_create(subtask, "Code");
|
||||
|
||||
/* slow things down */
|
||||
var sys_sleep = $loader.loadprim("std@sys_sleep", 1);
|
||||
var random_new = $loader.loadprim("std@random_new", 0);
|
||||
var random_int = $loader.loadprim("std@random_int", 2);
|
||||
|
||||
var randomsleep = function(message) {
|
||||
var r = random_new();
|
||||
var sleep = random_int(r, 3);
|
||||
sys_sleep(sleep);
|
||||
$print(message, "\n");
|
||||
}
|
||||
|
||||
$print("\nWith random delays\n");
|
||||
thread_create(randomsleep, "Enjoy");
|
||||
thread_create(randomsleep, "Rosetta");
|
||||
thread_create(randomsleep, "Code");
|
||||
|
||||
/* Let the threads complete */
|
||||
sys_sleep(4);
|
||||
10
Task/Concurrent-computing/Nim/concurrent-computing-1.nim
Normal file
10
Task/Concurrent-computing/Nim/concurrent-computing-1.nim
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
const str = ["Enjoy", "Rosetta", "Code"]
|
||||
|
||||
var thr: array[3, Thread[int32]]
|
||||
|
||||
proc f(i:int32) {.thread.} =
|
||||
echo str[i]
|
||||
|
||||
for i in 0..thr.high:
|
||||
createThread(thr[i], f, int32(i))
|
||||
joinThreads(thr)
|
||||
4
Task/Concurrent-computing/Nim/concurrent-computing-2.nim
Normal file
4
Task/Concurrent-computing/Nim/concurrent-computing-2.nim
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
const str = ["Enjoy", "Rosetta", "Code"]
|
||||
|
||||
for i in 0||2:
|
||||
echo str[i]
|
||||
9
Task/Concurrent-computing/Nim/concurrent-computing-3.nim
Normal file
9
Task/Concurrent-computing/Nim/concurrent-computing-3.nim
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import threadpool
|
||||
const str = ["Enjoy", "Rosetta", "Code"]
|
||||
|
||||
proc f(i: int) {.thread.} =
|
||||
echo str[i]
|
||||
|
||||
for i in 0..str.high:
|
||||
spawn f(i)
|
||||
sync()
|
||||
14
Task/Concurrent-computing/OCaml/concurrent-computing.ocaml
Normal file
14
Task/Concurrent-computing/OCaml/concurrent-computing.ocaml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
#directory "+threads"
|
||||
#load "unix.cma"
|
||||
#load "threads.cma"
|
||||
|
||||
let sleepy_print msg =
|
||||
Unix.sleep (Random.int 4);
|
||||
print_endline msg
|
||||
|
||||
let threads =
|
||||
List.map (Thread.create sleepy_print) ["Enjoy"; "Rosetta"; "Code"]
|
||||
|
||||
let () =
|
||||
Random.self_init ();
|
||||
List.iter (Thread.join) threads
|
||||
27
Task/Concurrent-computing/Objeck/concurrent-computing.objeck
Normal file
27
Task/Concurrent-computing/Objeck/concurrent-computing.objeck
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
bundle Default {
|
||||
class MyThread from Thread {
|
||||
New(name : String) {
|
||||
Parent(name);
|
||||
}
|
||||
|
||||
method : public : Run(param : Base) ~ Nil {
|
||||
string := param->As(String);
|
||||
string->PrintLine();
|
||||
}
|
||||
}
|
||||
|
||||
class Concurrent {
|
||||
New() {
|
||||
}
|
||||
|
||||
function : Main(args : System.String[]) ~ Nil {
|
||||
t0 := MyThread->New("t0");
|
||||
t1 := MyThread->New("t1");
|
||||
t2 := MyThread->New("t2");
|
||||
|
||||
t0->Execute("Enjoy"->As(Base));
|
||||
t1->Execute("Rosetta"->As(Base));
|
||||
t2->Execute("Code"->As(Base));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#[ "Enjoy" println ] &
|
||||
#[ "Rosetta" println ] &
|
||||
#[ "Code" println ] &
|
||||
|
|
@ -0,0 +1 @@
|
|||
[ "Enjoy", "Rosetta", "Code" ] mapParallel(#[ dup . size ])
|
||||
8
Task/Concurrent-computing/Ol/concurrent-computing.ol
Normal file
8
Task/Concurrent-computing/Ol/concurrent-computing.ol
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
(import (otus random!))
|
||||
|
||||
(for-each (lambda (str)
|
||||
(define timeout (rand! 999))
|
||||
(async (lambda ()
|
||||
(sleep timeout)
|
||||
(print str))))
|
||||
'("Enjoy" "Rosetta" "Code"))
|
||||
35
Task/Concurrent-computing/OoRexx/concurrent-computing.rexx
Normal file
35
Task/Concurrent-computing/OoRexx/concurrent-computing.rexx
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
-- this will launch 3 threads, with each thread given a message to print out.
|
||||
-- I've added a stoplight to make each thread wait until given a go signal,
|
||||
-- plus some sleeps to give the threads a chance to randomize the execution
|
||||
-- order a little.
|
||||
launcher = .launcher~new
|
||||
launcher~launch
|
||||
|
||||
::class launcher
|
||||
-- the launcher method. Guarded is the default, but let's make this
|
||||
-- explicit here
|
||||
::method launch guarded
|
||||
|
||||
runner1 = .runner~new(self, "Enjoy")
|
||||
runner2 = .runner~new(self, "Rosetta")
|
||||
runner3 = .runner~new(self, "Code")
|
||||
|
||||
-- let's give the threads a chance to settle in to the
|
||||
-- starting line
|
||||
call syssleep 1
|
||||
|
||||
guard off -- release the launcher lock. This is the starter's gun
|
||||
|
||||
-- this is a guarded method that the runners will call. They
|
||||
-- will block until the launch method releases the object guard
|
||||
::method block guarded
|
||||
|
||||
::class runner
|
||||
::method init
|
||||
use arg launcher, text
|
||||
reply -- this creates the new thread
|
||||
|
||||
call syssleep .5 -- try to mix things up by sleeping
|
||||
launcher~block -- wait for the go signal
|
||||
call syssleep .5 -- add another sleep here
|
||||
say text
|
||||
5
Task/Concurrent-computing/Oz/concurrent-computing.oz
Normal file
5
Task/Concurrent-computing/Oz/concurrent-computing.oz
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
for Msg in ["Enjoy" "Rosetta" "Code"] do
|
||||
thread
|
||||
{System.showInfo Msg}
|
||||
end
|
||||
end
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
inline(func);
|
||||
func(n)=print(["Enjoy","Rosetta","Code"][n]);
|
||||
parapply(func,[1..3]);
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
void
|
||||
foo()
|
||||
{
|
||||
if (pari_daemon()) {
|
||||
// Original
|
||||
if (pari_daemon()) {
|
||||
// Original
|
||||
pari_printf("Enjoy\n");
|
||||
} else {
|
||||
// Daemon #2
|
||||
pari_printf("Code\n");
|
||||
}
|
||||
} else {
|
||||
// Daemon #1
|
||||
pari_printf("Rosetta\n");
|
||||
}
|
||||
}
|
||||
60
Task/Concurrent-computing/Pascal/concurrent-computing.pas
Normal file
60
Task/Concurrent-computing/Pascal/concurrent-computing.pas
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
program ConcurrentComputing;
|
||||
{$IFdef FPC}
|
||||
{$MODE DELPHI}
|
||||
{$ELSE}
|
||||
{$APPTYPE CONSOLE}
|
||||
{$ENDIF}
|
||||
uses
|
||||
{$IFDEF UNIX}
|
||||
cthreads,
|
||||
{$ENDIF}
|
||||
SysUtils, Classes;
|
||||
|
||||
type
|
||||
TRandomThread = class(TThread)
|
||||
private
|
||||
FString: string;
|
||||
T0 : Uint64;
|
||||
protected
|
||||
procedure Execute; override;
|
||||
public
|
||||
constructor Create(const aString: string); overload;
|
||||
end;
|
||||
const
|
||||
MyStrings: array[0..2] of String = ('Enjoy ','Rosetta ','Code ');
|
||||
var
|
||||
gblRunThdCnt : LongWord = 0;
|
||||
|
||||
constructor TRandomThread.Create(const aString: string);
|
||||
begin
|
||||
inherited Create(False);
|
||||
FreeOnTerminate := True;
|
||||
FString := aString;
|
||||
interlockedincrement(gblRunThdCnt);
|
||||
end;
|
||||
|
||||
procedure TRandomThread.Execute;
|
||||
var
|
||||
i : NativeInt;
|
||||
begin
|
||||
i := Random(300);
|
||||
T0 := GettickCount64;
|
||||
Sleep(i);
|
||||
//output of difference in time
|
||||
Writeln(FString,i:4,GettickCount64-T0 -i:2);
|
||||
interlockeddecrement(gblRunThdCnt);
|
||||
end;
|
||||
|
||||
var
|
||||
lThreadArray: Array[0..9] of THandle;
|
||||
i : NativeInt;
|
||||
begin
|
||||
Randomize;
|
||||
|
||||
gblRunThdCnt := 0;
|
||||
For i := low(lThreadArray) to High(lThreadArray) do
|
||||
lThreadArray[i] := TRandomThread.Create(Format('%9s %4d',[myStrings[Random(3)],i])).Handle;
|
||||
|
||||
while gblRunThdCnt > 0 do
|
||||
sleep(125);
|
||||
end.
|
||||
9
Task/Concurrent-computing/Perl/concurrent-computing-1.pl
Normal file
9
Task/Concurrent-computing/Perl/concurrent-computing-1.pl
Normal 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);
|
||||
10
Task/Concurrent-computing/Perl/concurrent-computing-2.pl
Normal file
10
Task/Concurrent-computing/Perl/concurrent-computing-2.pl
Normal 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 );
|
||||
18
Task/Concurrent-computing/Phix/concurrent-computing.phix
Normal file
18
Task/Concurrent-computing/Phix/concurrent-computing.phix
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
(notonline)-->
|
||||
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (threads)</span>
|
||||
<span style="color: #008080;">procedure</span> <span style="color: #000000;">echo</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #7060A8;">enter_cs</span><span style="color: #0000FF;">()</span>
|
||||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #7060A8;">leave_cs</span><span style="color: #0000FF;">()</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
|
||||
|
||||
<span style="color: #008080;">constant</span> <span style="color: #000000;">threads</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">create_thread</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"echo"</span><span style="color: #0000FF;">),{</span><span style="color: #008000;">"Enjoy"</span><span style="color: #0000FF;">}),</span>
|
||||
<span style="color: #000000;">create_thread</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"echo"</span><span style="color: #0000FF;">),{</span><span style="color: #008000;">"Rosetta"</span><span style="color: #0000FF;">}),</span>
|
||||
<span style="color: #000000;">create_thread</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"echo"</span><span style="color: #0000FF;">),{</span><span style="color: #008000;">"Code"</span><span style="color: #0000FF;">})}</span>
|
||||
|
||||
<span style="color: #000000;">wait_thread</span><span style="color: #0000FF;">(</span><span style="color: #000000;">threads</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"done"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
|
||||
<!--
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
11
Task/Concurrent-computing/Pike/concurrent-computing-1.pike
Normal file
11
Task/Concurrent-computing/Pike/concurrent-computing-1.pike
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
int main() {
|
||||
// Start threads and wait for them to finish
|
||||
({
|
||||
Thread.Thread(write, "Enjoy\n"),
|
||||
Thread.Thread(write, "Rosetta\n"),
|
||||
Thread.Thread(write, "Code\n")
|
||||
})->wait();
|
||||
|
||||
// Exit program
|
||||
exit(0);
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
int main(int argc, array argv)
|
||||
{
|
||||
call_out(write, random(1.0), "Enjoy\n");
|
||||
call_out(write, random(1.0), "Rosetta\n");
|
||||
call_out(write, random(1.0), "Code\n");
|
||||
call_out(exit, 1, 0);
|
||||
return -1; // return -1 starts the backend which makes Pike run until exit() is called.
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
$Strings = "Enjoy","Rosetta","Code"
|
||||
|
||||
$SB = {param($String)Write-Output $String}
|
||||
|
||||
foreach($String in $Strings) {
|
||||
Start-Job -ScriptBlock $SB -ArgumentList $String | Out-Null
|
||||
}
|
||||
|
||||
Get-Job | Wait-Job | Receive-Job
|
||||
Get-Job | Remove-Job
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
$Strings = "Enjoy","Rosetta","Code"
|
||||
|
||||
$SB = {param($String)Write-Output $String}
|
||||
|
||||
$Pool = [RunspaceFactory]::CreateRunspacePool(1, 3)
|
||||
$Pool.ApartmentState = "STA"
|
||||
$Pool.Open()
|
||||
foreach ($String in $Strings) {
|
||||
$Pipeline = [System.Management.Automation.PowerShell]::create()
|
||||
$Pipeline.RunspacePool = $Pool
|
||||
[void]$Pipeline.AddScript($SB).AddArgument($String)
|
||||
$AsyncHandle = $Pipeline.BeginInvoke()
|
||||
$Pipeline.EndInvoke($AsyncHandle)
|
||||
$Pipeline.Dispose()
|
||||
}
|
||||
$Pool.Close()
|
||||
12
Task/Concurrent-computing/Prolog/concurrent-computing.pro
Normal file
12
Task/Concurrent-computing/Prolog/concurrent-computing.pro
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
main :-
|
||||
thread_create(say("Enjoy"),A,[]),
|
||||
thread_create(say("Rosetta"),B,[]),
|
||||
thread_create(say("Code"),C,[]),
|
||||
thread_join(A,_),
|
||||
thread_join(B,_),
|
||||
thread_join(C,_).
|
||||
|
||||
say(Message) :-
|
||||
Delay is random_float,
|
||||
sleep(Delay),
|
||||
writeln(Message).
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
Global mutex = CreateMutex()
|
||||
|
||||
Procedure Printer(*str)
|
||||
LockMutex(mutex)
|
||||
PrintN( PeekS(*str) )
|
||||
UnlockMutex(mutex)
|
||||
EndProcedure
|
||||
|
||||
If OpenConsole()
|
||||
LockMutex(mutex)
|
||||
thread1 = CreateThread(@Printer(), @"Enjoy")
|
||||
thread2 = CreateThread(@Printer(), @"Rosetta")
|
||||
thread3 = CreateThread(@Printer(), @"Code")
|
||||
UnlockMutex(mutex)
|
||||
|
||||
WaitThread(thread1)
|
||||
WaitThread(thread2)
|
||||
WaitThread(thread3)
|
||||
|
||||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
|
||||
Input()
|
||||
|
||||
CloseConsole()
|
||||
EndIf
|
||||
|
||||
FreeMutex(mutex)
|
||||
15
Task/Concurrent-computing/Python/concurrent-computing-1.py
Normal file
15
Task/Concurrent-computing/Python/concurrent-computing-1.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import asyncio
|
||||
|
||||
|
||||
async def print_(string: str) -> None:
|
||||
print(string)
|
||||
|
||||
|
||||
async def main():
|
||||
strings = ['Enjoy', 'Rosetta', 'Code']
|
||||
coroutines = map(print_, strings)
|
||||
await asyncio.gather(*coroutines)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
10
Task/Concurrent-computing/Python/concurrent-computing-2.py
Normal file
10
Task/Concurrent-computing/Python/concurrent-computing-2.py
Normal 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
|
||||
>>>
|
||||
|
|
@ -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()
|
||||
|
|
@ -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()
|
||||
14
Task/Concurrent-computing/Python/concurrent-computing-5.py
Normal file
14
Task/Concurrent-computing/Python/concurrent-computing-5.py
Normal 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()
|
||||
|
|
@ -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()
|
||||
|
|
@ -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()
|
||||
|
|
@ -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()])
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#lang racket
|
||||
(for ([str '("Enjoy" "Rosetta" "Code")])
|
||||
(thread (λ () (displayln str))))
|
||||
2
Task/Concurrent-computing/Raku/concurrent-computing.raku
Normal file
2
Task/Concurrent-computing/Raku/concurrent-computing.raku
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
my @words = <Enjoy Rosetta Code>;
|
||||
@words.race(:batch(1)).map: { sleep rand; say $_ };
|
||||
10
Task/Concurrent-computing/Raven/concurrent-computing.raven
Normal file
10
Task/Concurrent-computing/Raven/concurrent-computing.raven
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[ 'Enjoy' 'Rosetta' 'Code' ] as $words
|
||||
|
||||
thread talker
|
||||
$words pop "%s\n"
|
||||
repeat dup print
|
||||
500 choose ms
|
||||
|
||||
talker as a
|
||||
talker as b
|
||||
talker as c
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue