View Category

Subdivide A Problem To A Pool Of Workers (No Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.

Example:

-Input-

(In python syntax)

["ab", "we", "tfe", "aoj"]

In other words, a list of random strings.

-Output-

(In python syntax)

[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...

In other words, all possible permutations of each input string are computed.

Subdivide A Problem To A Pool Of Workers (Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.

Example:

-Conway Game of Life-

From Wikipedia:

The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.


--However, for our purposes, we will assign a size to the game "board": 2^k * 2^k . That is, the board should be easy to subdivide.

Notice that in this problem, at each step or "tick", each thread/process will need to share data with its neighborhood.

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.
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 ()

Create read/write lock on a shared resource.

Create multiple threads or processes who are either readers or writers. There should be more readers then writers.

(From Wikipedia):

Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.

Example:

-Output-

Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...

--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
ocaml

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

let value = ref 8
let mutex = Mutex.create ()

let create_writer i =
if not (Mutex.try_lock mutex) then begin
Printf.printf "Thread %d tried to write the value but could not.\n" i;
Mutex.lock mutex
end;
value := Random.int 10;
Printf.printf "Thread %d is changing the value to %d\n" i !value;
Mutex.unlock mutex;
Printf.printf "Thread %d is releasing the lock.\n" i

let create_reader i =
if not (Mutex.try_lock mutex) then begin
Printf.printf "Thread %d tried to read the value but could not.\n" i;
Mutex.lock mutex
end;
Printf.printf "Thread %d says that the value is %d\n" i !value;
Mutex.unlock mutex
;;

let thread_ids = Array.init 20 (fun i ->
Thread.create (if i mod 3 == 0 then create_writer else create_reader) i) in
Array.iter Thread.join thread_ids

Separate user interaction and computation.

Allow your program to accept user interaction while conducting a long running computation.

Example:

Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I'll let my worker thread know... (input thread)
We'
re quitting! Alright! (worker thread)

--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
ocaml
(* Compile (native):
$ ocamlopt -thread unix.cmxa threads.cmxa async_interface.ml -o async_interface
*)

module Mailbox =
struct

type 'a t = {
lock: Mutex.t;
notempty_condition: Condition.t;
queue: 'a Queue.t;
}

let create () = {
lock = Mutex.create ();
notempty_condition = Condition.create ();
queue = Queue.create ();
}

let add mb v =
Mutex.lock mb.lock;
Queue.add v mb.queue;
Condition.signal mb.notempty_condition;
Mutex.unlock mb.lock

let take mb =
Mutex.lock mb.lock;
while Queue.is_empty mb.queue do
Printf.printf "(waiting)\n%!";
Condition.wait mb.notempty_condition mb.lock
done;
let v = Queue.take mb.queue in
Mutex.unlock mb.lock;
v
end

type 'a orders =
Process of 'a
| Terminate

let permute_string s buf =
let len = String.length s in
let sep = ref "" in
let rec aux i =
if i = 0 then begin
Buffer.add_string buf !sep;
Buffer.add_char buf '"';
Buffer.add_string buf s;
Buffer.add_char buf '"';
sep := ","
end
else
let c = s.[i] in
for j = 0 to i - 1 do
s.[i] <- s.[j];
s.[j] <- c;
aux (i - 1);
s.[j] <- s.[i]
done;
s.[i] <- c;
aux (i - 1)
in
if len > 0 then
aux (len - 1)

let rec slave_loop mailbox =
match Mailbox.take mailbox with
| Process s ->
Printf.printf "Working on %s...%!" s;
let len = String.length s in
let fact n =
let rec aux i acc =
if i < 2 then acc
else aux (i - 1) (acc * i) in
aux n 1 in
(* Buffers reallocate as needed, but since we know the size beforehand... *)
let expected_output_size = (len + 3) * (fact len) + 2 in
let buf = Buffer.create expected_output_size in
Buffer.add_char buf '[';
permute_string s buf;
Buffer.add_string buf "]\n";
Printf.printf " Done Work On %s!\n" s;
Buffer.output_buffer stdout buf;
flush stdout;
slave_loop mailbox
| Terminate ->
Printf.printf "%s\n%!" "We're quitting! Alright!"


let rec master_loop mailbox article =
Printf.printf "Please input %s string to permute: %!" article;
let exit_string = "EXIT" in
let s =
try
read_line ()
with End_of_file -> exit_string in
if s = exit_string then begin
Printf.printf "%s\n%!" "Quitting, I'll let my worker thread know";
Mailbox.add mailbox Terminate
end
else begin
Printf.printf "Passing on %s...\n%!" s;
Mailbox.add mailbox (Process s);
master_loop mailbox "another"
end

let () =
let mailbox = Mailbox.create () in
let slave_thread_id = Thread.create slave_loop mailbox in

print_string "Hello user! ";
master_loop mailbox "a";

Thread.join slave_thread_id