View Problem

Create a multithreaded "Hello World"

Create a program which outputs the string "Hello World" to the console, multiple times, using separate threads or processes.

Example:

-Output-

Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!

-Notice that the threads can print in any order.
DiskEdit
clojure
(doseq [msg ["one" "two" "three" "four"]]
(future (println "Thread" msg "says Hello World!")))
DiskEdit
clojure
(dorun (pmap #(println (str "Thread " % " says Hello World!")) '("one" "two" "three" "four")))
ExpandDiskEdit
clojure
(dorun (map (fn [n] (.start (Thread. #(println (str "Thread " n " says Hello World!")))))
'("one" "two" "three" "four")))
DiskEdit
cpp
#include <iostream>
#include <string>

using namespace std;

int main(){
int pid;
string text[4]={"one","two","three","four"};
for (int i=0;i<4;i++){
pid=fork();
if (pid>0){
//cout << "Process("<<pid<<") - " << "Thread " << text[i] << " says Hello World!" << endl;
cout << "Thread " << text[i] << " says Hello World!" << endl;
exit(0);
}
}
return 0;
}
DiskEdit
cpp
#include <iostream>
#include <string>

#include <omp.h>

int main() {
unsigned int const num_threads = 4;

std::string const names[] = { "one", "two", "three", "four" };

# pragma omp parallel num_threads(num_threads)
{
unsigned const id = omp_get_thread_num();
// Stream concatenation isn't thread-safe so we use a critical section.
# pragma omp critical
std::cout << "Thread " << names[id] << " says Hello World!" << std::endl;
}
}
DiskEdit
erlang
-module(spam).
-export([spam/1]).

spam(N) when N<5 ->
spawn(fun() -> io:format("Hello World from thread ~p~n",[N]) end),
spam(N+1);
spam(_) -> void.
ExpandDiskEdit
fantom
pool := ActorPool()
["one", "two", "three", "four"].each
{
a := Actor(pool) |Str name| { echo("Thread $name says Hello World!") }
a.send(it)
}
DiskEdit
fsharp
let mappedString =
["Thread one says Hello World!";
"Thread two says Hello World!";
"Thread four says Hello World!";
"Thread three says Hello World!"]
|> Seq.map (fun str -> async { printfn "%s" str })

Async.RunSynchronously (Async.Parallel mappedString)
DiskEdit
groovy
["one","two","three","four"].each { tid ->
Thread.start {
println "Thread $tid says Hello World!"
}
}
DiskEdit
groovy with gpars
import static groovyx.gpars.Parallelizer.*
withParallelizer {
["one","two","three","four"].eachParallel {
println "Thread $it says Hello World!"
}
}
DiskEdit
haskell
mapM_ (\x -> forkIO (putStrLn ("Thread " ++ x ++ " says Hello World!"))) ["one", "two", "three", "four"]
DiskEdit
java
for (int i = 0; i < 4; i++) {
final int nr = i ;
new Thread(new Runnable() {
public void run() {
System.out.println("Thread " + new String[] { "one", "two", "three", "four" }[nr] + " says Hello World!");
}
}).start();
}
DiskEdit
ocaml

(* Compilation (native):
$ ocamlopt -thread unix.cmxa threads.cmxa threads_hello.ml -o threads_hello
*)

let say_hello (i, msg) =
Printf.printf "Thread %d says %s\n" i msg
;;
let thread_ids = Array.init 4 (fun i ->
Thread.create say_hello (i, "Hello World!")) in
Array.iter Thread.join thread_ids;
flush_all ()
DiskEdit
perl >= 5.8
use threads;

foreach my $tid ("one","two","three","four") {
threads->create(
sub { print("Thread $tid says Hello World!\n"); }
)->join();
}
ExpandDiskEdit
php 4.1.0 or higher
/*
The commented lines below can be used to verify new process are in use
*/
$text=array("one","two","three","four");
for ($i = 0; $i < 4; ++$i) {
$pid = pcntl_fork();
//$mypid=getmypid();
if (!$pid) {
//echo("Thread ".$text[$i]." says Hello World!(".$mypid.")\n");
echo("Thread ".$text[$i]." says Hello World!\n");
exit($i);
}
}
DiskEdit
python
#!/usr/bin/python
from threading import Thread
Nthread = ['one','two','three','four']
def ThreadSpeaks(number):
print "Thread", number, "says Hello World!"
if __name__ == "__main__":
for n in range(0,len(Nthread)):
th =Thread(target=ThreadSpeaks, args=(Nthread[n],))
th.start()
DiskEdit
ruby
%w[one two three four].each do |number|
Thread.new(number) { |number|
puts "Thread #{number} says Hello World!"
}.join
end
DiskEdit
scala with Actors
import scala.actors.Actor

List("one", "two", "three", "four").foreach { name =>
new Actor { override def act() = { println("Thread " + name + " says Hello World!") } }.start
}
DiskEdit
scala with Threads
List("one", "two", "three", "four").foreach { name =>
new Thread { override def run() = { println("Thread " + name + " says Hello World!") } }.start
}
DiskEdit
scala with future
import scala.actors.Futures._
List("one", "two", "three", "four").foreach(name => future(println("Thread " + name + " says hi")))

Submit a new solution for clojure, cpp, erlang, fantom ...