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.
groovy
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]
def threads = []

void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}

words.each { word ->
def t = Thread.start {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
threads << t
}

threads.each{ it.join() }
println ans
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]

void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}

withParallelizer {
words.eachParallel { word ->
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
}

println ans

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.
groovy
// some crude assumptions made for size and amount of parallelism
enum State { ALIVE, DEAD }
import static State.*

seed = '''\
* *
** **
** *
*
**
***
**
* \
'''

def computeNextGen(inboard, outboard, n) {
// crudely split into 4 chunks but could be smarter if we wanted
int half = n/2
def t1 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, 0, half) }
def t2 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, half, n) }
def t3 = Thread.start { computeNextGen(inboard, outboard, n, half, n, 0, half) }
def t4 = Thread.start { computeNextGen(inboard, outboard, n, half, n, half, n) }
[t1, t2, t3, t4].each{ it.join() }
}

def computeNextGen(inboard, outboard, n, minx, maxx, miny, maxy) {
for (int i = minx; i < maxx; i++)
for (int j = 0; j < maxy; j++)
if (i == 0 || i == n-1 || j == 0 || j == n-1)
outboard[i][j] = DEAD
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
if (i == 0 || i == n-1 || j == 0 || j == n-1)
continue
int count = 0
[[-1, 0, 1], [-1, 0, 1]].combinations().each{ dx, dy ->
if ((dx || dy) && inboard[i+dx][j+dy] == ALIVE) count++
}
switch(count) {
case {count == 3}:
case {inboard[i][j] == ALIVE && count == 2}:
outboard[i][j] = ALIVE; break
default:
outboard[i][j] = DEAD
}
}
}
}

void printBoard(board) {
println '--------'
println board*.collect{ it == DEAD ? ' ' : '*' }*.join().join('\n')
}

void initBoard(seed, board) {
def row = 0
seed.readLines().each { line ->
def col = 0
line.each { ch ->
board[row][col++] = ch == '*' ? ALIVE : DEAD
}
row++
}
}

def N = 8
def NUM_CYCLES = 3
def board1 = new State[N][N]
def board2 = new State[N][N]
initBoard(seed, board1)
NUM_CYCLES.times {
computeNextGen board1, board2, N
printBoard board2
computeNextGen board2, board1, N
printBoard board1
}

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.
groovy
["one","two","three","four"].each { tid ->
Thread.start {
println "Thread $tid says Hello World!"
}
}
import static groovyx.gpars.Parallelizer.*
withParallelizer {
["one","two","three","four"].eachParallel {
println "Thread $it says Hello World!"
}
}

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.
groovy
def lock = new ReentrantLock()
Integer value = 8

20.times { i ->
if (i % 3 == 0) {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to write the value, but could not."
lock.lock()
}
value = (int) (Math.random() * 10)
println "Thread " + i + " is changing the value to " + value
lock.unlock()
println "Thread " + i + " is releasing the lock."
}
} else {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to read the value, but could not."
lock.lock()
}
println "Thread " + i + " says that the value is " + value + "."
lock.unlock()
}
}
}

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.
groovy
def threads = new ConcurrentLinkedQueue<Thread>()

void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}

println 'Welcome to the parallel permuter'
System.in.withReader { r ->
while (true) {
print 'Enter word:'
def word = r.readLine()
if (word == 'EXIT') {
while (!threads.isEmpty())
threads.poll().stop(new ThreadDeath())
break
} else
threads << Thread.start {
try {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
println '\nAnswer:' + wordAns
print 'Enter word:'
} catch (ThreadDeath td) {
println 'Thread aborted!'
}
}
}
}