View Subcategory

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.
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()
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;
}
#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;
}
}

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.
python
#!/usr/bin/python
from threading import Thread, Lock
import time
thread_readers = ['one','two','three']
thread_writer = ['four','five']
lock = Lock()
value = 0

def Threadread(number):
global value
while True:
if lock.acquire(False):
print "Thread", number, "is taking the lock"
value += 1
print "Thread", number, "is changing the value to", value
print "Thread", number, "is releasing the lock."
lock.release()
else:
print "Thread", number, "tried to write to the value, but could not."
def Threadwrite(number):
global value
while True:
if lock.acquire(False):
print "Thread", number ,"four says that the value is", value
else:
print "Thread", number ,"tried to read the value, but could not."
if __name__ == "__main__":
for n in range(0,len(thread_readers)):
th =Thread(target=Threadread, args=(thread_readers[n],))
th.start()
for n in range(0,len(thread_writer)):
th =Thread(target=Threadwrite, args=(thread_writer[n],))
th.start()
cpp
class reader
{
string name_;
public:
reader(const string& name) : name_(name) {}

void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
shared_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
cout << " says that the value is " << shared_value << "." << endl;
else
cout << " tried to read the value, but could not." << endl;
}
}
};

class writer
{
string name_;
public:
writer(const string& name) : name_(name) {}
void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
unique_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
{
cout << " is taking the lock." << endl;
shared_value = rand() % 10;
cout << "Thread " << name_ << " is changing the value to " << shared_value << endl;
cout << "Thread " << name_ << " is releasing the lock. " << endl;
}
else
cout << " tried to write to the value, but could not." << endl;
}
}
};

int main()
{
thread t1 = thread(reader("one"));
thread t2 = thread(reader("two"));
thread t3 = thread(reader("three"));
thread t4 = thread(writer("four"));
writer("five")();
}

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.
cpp
class bg_worker
{
mutex bg_mutex_;
condition_variable work_present_;
deque<string> work_queue_;

result calc_perm(string s) {
result perms = result(new list<string>());

// sleep to simulate lots of work...
this_thread::sleep(posix_time::seconds(3));
sort(s.begin(), s.end());
do {
perms->push_back(s);
} while (next_permutation(s.begin(), s.end()));
return perms;
}

public:
void submit_work(const string &s) {
lock_guard<mutex> lock(bg_mutex_);
work_queue_.push_back(s);
work_present_.notify_one();
}

void operator()() {
for (;;) {
unique_lock<mutex> lock(bg_mutex_);
while (work_queue_.empty())
work_present_.wait(lock);
string s = work_queue_.front();
work_queue_.pop_front();
lock.unlock();

if (s == "EXIT") {
lock_guard<mutex> cout_lock(cout_mutex);
cout << "We're quitting! Alright!" << endl;
break;
}

result perm = calc_perm(s);
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Done Work On " << s << "!" << endl;
cout << perm << endl;
}
}
};

int main()
{
bg_worker worker;
thread bg_thr(boost::ref(worker));
bool done = false;

{
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Hello user! Please input a string to permute:" << endl;
}

while (!done)
{
string input;
cin >> input;
{
lock_guard<mutex> cout_lock(cout_mutex);
if (input == "EXIT") {
cout << "Quitting, I'll let my worker thread know..." << endl;
done = true;
} else {
cout << "Passing on " << input << "..." << endl;
cout << "Please input another string to permute:" << endl;
}
}
worker.submit_work(input);
}

bg_thr.join();
}