PDA

View Full Version : Concurrent "Hello World"


file13
06-17-2002, 11:54 PM
1. pick a language
2. set up 3 different threads, one that prints "Hello", one that prints "Concurrent", and one that prints "World!" each on a new line.
3. after each task is started setup a random delay between 0.0 to 1.0 seconds before it prints the output so the words are not necessarily printed in the correct order.

sample output:


[file13@anatta tmp]$ time ./hellotask
Concurrent
World!
Hello
0.01user 0.00system 0:00.45elapsed 2%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (294major+49minor)pagefaults 0swaps
[file13@anatta tmp]$ time ./hellotask
Concurrent
Hello
World!
0.01user 0.00system 0:00.36elapsed 2%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (294major+49minor)pagefaults 0swaps


since many languages don't have built in concurrency you'll have to rely on stuff like pthreads. please note which bindings you use and please create "makefiles" (or make.bat files). or clearly state the building process in the source.

good luck!

(thanks to James Rogers for the idea!)

(better? ;) )

Nafae
06-18-2002, 12:08 AM
If you already knew this i'm sorry, but you can put your code examples in [ code ] tags if you like :) Just seperates it from the other text better.

file13
06-18-2002, 01:54 PM
here's it in Ada 95 (which does have built in concurrency.... ;))


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;

procedure Hellotask is

Seed : Generator;

task type Delayed_Displayer is
entry Start (Word : String);
end Delayed_Displayer;

task body Delayed_Displayer is
Tmp : Unbounded_String;
begin
accept Start (Word : String)
do
Tmp := To_Unbounded_String (Word);
end Start;
delay Duration (Random (Seed));
Put_Line (To_String (Tmp));
end Delayed_Displayer;

Word1, Word2, Word3 : Delayed_Displayer;

begin
Reset (Seed);
Word1.Start ("Hello");
Word2.Start ("Concurrent");
Word3.Start ("World!");
end Hellotask;


:)

build instructions under GNAT:


gnatmake hellotask


http://www.gnat.com/

Dru Lee Parsec
06-18-2002, 05:06 PM
OK, here's a very similar program that I wrote quite a while ago for codeexamples.org. It sets up 3 panels (In a GUI!) each with it's own thread. Each panel has a start and a stop button. each panel will display an ever increasing integer but each panel does it at a different speed.

You can start and stop each thread independently of the other.

Save this code as ThreadDemo.java (including that capitalization). The build command is

javac ThreadDemo.java

The run command is

java ThreadDemo

provided that the ThreadDemo.class file is in your class path. IF not then yo ucan run it like this:

java -cp . ThreadDemo

Here's the code


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ThreadDemo
{
public static void main(String args[])
{
JFrame mainframe = new JFrame("Thread Demo");
mainframe.setSize(500, 250);
mainframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
JPanel mainPanel = new JPanel(new GridLayout(3,1));
mainPanel.add(new ThreadPanel(100, "Fast Panel"));
mainPanel.add(new ThreadPanel(250, "Medium Panel"));
mainPanel.add(new ThreadPanel(1000, "Slow Panel"));
mainframe.getContentPane().add(mainPanel);
mainframe.setVisible(true);
}
}

class ThreadPanel extends JPanel implements Runnable {
private JButton startButton = new JButton("Start");
private JButton stopButton = new JButton("Stop");
private JLabel label = new JLabel();
private int delay = 0;
private String borderText;
private int count = 0;

public ThreadPanel(int delay, String borderText){
this.delay = delay;
this.borderText = borderText;
buildUI();
buildListeners();
}

private Thread timerThread = null;
private void start() {
if (timerThread == null) {
timerThread = new Thread(this, "Timer");
timerThread.start();
}
}
public void run() {
Thread myThread = Thread.currentThread();
while (timerThread == myThread) {
label.setText(" " + count++ );
try {
Thread.sleep(delay);
} catch (InterruptedException e){
// the VM doesn't want us to sleep anymore,
// so get back to work
}
}
}

private void stop() {
timerThread = null;
}

private void buildUI(){
setLayout(new GridLayout(1,3));
label.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(5,5,5,5)));
add(label);
add(startButton);
add(stopButton);
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder()
, borderText),
BorderFactory.createEmptyBorder(5,5,5,5)
));
}

private void buildListeners(){
startButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
start();
}
});

stopButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
stop();
}
});
}
}


I hope 92 lines isn't too long. Most of it is the code which builds the GUI. Still, 92 lines for a triple threaded GUI isn't too bad. ;)

file13
06-18-2002, 06:03 PM
nice! :)

Strike
06-20-2002, 01:19 PM
Moo:

#!/usr/bin/env python

import threading

def myPrint(str):
print str

myThreads = (threading.Thread(None, myPrint("hello")), \
threading.Thread(None, myPrint("concurrent")), \
threading.Thread(None, myPrint("world")))

for thr in myThreads:
thr.start()

kmj
06-20-2002, 01:31 PM
Strike: you could avoid having to create myPrint by simply using sys.stdout.write(...), correct?

file13
06-20-2002, 01:43 PM
nice Strike. but where's the random delay? :)

Strike
06-20-2002, 02:18 PM
oh, whoops, skipped that last part
will be a cinch to add

Strike
06-20-2002, 02:18 PM
kmj: yeah, I hadn't thought of that, good call

mine's a little more readable though, IMO ;) not that this is a big program or anything

Strike
06-20-2002, 02:26 PM
I used some stuff that's Python 2.2 specific, but here's the new output with randomness:

[ddipaolo@strike ..t/concurrent-hw]% python2.2 concurrent-hw.py
hello
concurrent
world
[ddipaolo@strike ..t/concurrent-hw]% python2.2 concurrent-hw.py
concurrent
world
hello
[ddipaolo@strike ..t/concurrent-hw]% python2.2 concurrent-hw.py
hello
world
concurrent
[ddipaolo@strike ..t/concurrent-hw]% python2.2 concurrent-hw.py
world
hello
concurrent


And the new code:

#!/usr/bin/env python2.2

import threading, random

def myPrint(str):
print str

myThreads = (threading.Timer(random.random(), myPrint, ["hello"]), \
threading.Timer(random.random(), myPrint, ["concurrent"]), \
threading.Timer(random.random(), myPrint, ["world"]))

for thr in myThreads:
thr.start()

stuka
06-24-2002, 11:47 AM
OK, here's mine (in C, with pthreads):include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>

void * print_msg(void *message);

int main()
{
int i;
pthread_t threads[3];
static char *msgs[] = { "Hello", "World", "Concurrent" };

srand(time(NULL));

for (i = 0; i < 3; i++)
{
pthread_create((threads + i), NULL, print_msg, msgs[i]);
}
for (i = 0; i < 3; i++) pthread_join(threads[i], NULL);
return (0);
}

void *print_msg(void *message)
{
usleep(rand() % 30000);
printf("%s\n", (char*)message);
}

And the build command: gcc -Wall -lpthreads -o hwc hwc.c