Simple Multi-Threaded Application in Haskell

July 27, 2010

Haskell has a powerful concurrency library which is surprisingly easy to use. The Control.Concurrent library is shipped with the standard installation of ghc and provides everything needed to get started.

As a small test I want to write a programme which reads numbers from stdin, spawns a new process to calculate the Fibonacci number for each input on a different CPU and prints the result to stdout.

First we need a function which is called when spawning a new process, which should calculate the result and print it to the console. In my case this is a simple IO Monad, which gets a MVar as it’s first argument. The function will wait for input from the MVar and then call the Fibonacci function.

This MVar can be thought of as a synchronised box where a thread can store a value and another thread can read from it. So MVars are just the poor men’s message channel which can hold one value at the time only. Of course there are also real channels in Haskell which act like the message queues in Scala or Erlang, see Control.Concurrent.Chan for more informations.

printResult mvar =  do
	value <- takeMVar mvar
	print $ "fib(" ++ show value ++ ")=" ++ show (fib value)

fib 0 = 0
fib 1 = 1
fib n =  fib (n - 1) + fib (n - 2)

Now we need to read the input from stdin, create a MVar object and invoke the printResult function. The cool thing about Haskell is the forkIO function which is really convenient. It takes an arbitrary IO expr and invokes it in a new thread:

import Control.Monad -- needed for "forever"
import System.Exit     -- needed for exitSuccess

main = forever $ do
	line <- getLine
	when (line == "quit") exitSuccess
	mvar <- newEmptyMVar
	forkIO $ printResult mvar
	putMVar mvar (read line :: Integer)

Now we have to compile our programme with the “-threaded” flag:

ghc -threaded fib.hs -o fib

The RTS allows us now to define the number of processors the application runs on with the -Nnum flag. If I want to use three processors for parallelisation I can run the programme simply with:

./fib +RTS -N4

Writing A Synthesizer With Brainfuck

June 2, 2010

Brainfuck is a small esoteric programming language which comes with just eight commands and Turing completeness (given enough time or memory). And that is just enough to write a small synthesizer in it. Some people have definitely too much time ;-)

Easter Eggs in Open Source Software

March 16, 2010

Some programmers definitely have to much time, see this link to an arstechnica article:

Cracking open five of the best open source easter eggs

Reinventing Human-Computer Interaction

February 19, 2010

Many of you probably remember “Minority Report”, a mediocre science fiction film inspired by a short story of good old Philip K. Dick. The only thing I really remember well about this movie is the huge multi-touch computer used by the police force (or something). Although such sci-fi devices look great they are a total nightmare for every day use. Just imagine you have to lift your arms every time you try to switch to another tab page of your browser. That is not really a solution. But how can we use awesome looking multi-touch devices in combination with our other hardware? Here is a small video which came up with some cool and fresh ideas:

reinventing desktop human-computer interaction: 10/GUI

Java & Multicore

February 15, 2010

Recently I needed to run some very CPU intensive calculations in Java. In order to harvest the full power of my multicore machine I took a look at Java’s concurrent package. I never used this package before. Either I had some convenient third party library functions at my hand which successfully were able to hide all the multithreading stuff from me, sometimes I struggled with Thread, Runnable and synchronized statements or … I just used another language :P

So here are my results from a short trip into the adventurous realm of multicore programming in Java. To make things a little bit simpler in this post I will demonstrate to run several functions calculating a high Fibonacci number instead of using a more complicated real world example. The calculations will be distributed via a thread pool and all classes used in this example belong to the Java standard library, so there won’t be a need to install any extra packages.

Read the rest of this entry »

Struggling with HTML or How To Use Vertical And Horizontal Alignment In CSS

January 28, 2010

HTML wasn’t invented to write interactive, application-like web pages, it just offers a convenient way to create really simple documents containing links. Maybe that’s why programming web pages nowadays feels a little bit like writing a GUI in LaTeX. But maybe I am just complaining because I am not used to it … I am a software developer, not a web designer.

Read the rest of this entry »

What is the most popular programming language?

January 26, 2010

Well, the answer is Java … according to the TIOBE Programming Community Index. Other statistics also announce Java as the most popular one. C/C++ is following closely but is still behind Java. Surprisingly PHP is in many charts on the next place while Perl and Python are struggling for being the most popular scripting language. However Ruby seems to continue it’s rise to conquer the world, although slowing down in the last months.

Here is a chart showing the long term trend of programming languages:

from http://www.tiobe.com

OK, so Java and Perl are slowly dying out. But who is replacing these languages? On the one hand Python and Ruby finally seem to get the attention they deserve. C# is also becoming more popular and is growing in a very stable rate. I think the development of C is interesting. The rapidly growing mobile market may be one reason why this language is still that popular. In the time of web application, plugins and powerful CPUs I would expect C to lose “market share” among the programmer community, but that doesn’t seem to happen.

Java: Casting to Array

December 10, 2009

OK, here’s the problem:

I want to convert a List to an Integer[]:

List<Integer> intList = ...
Integer[] intArray = (Integer[]) intList.toArray();

throws: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

This code doesn't work, because of type incompatibility. The method toArray() returns an Object[] array but I want to have an Integer[] array instead. The solution is a little bit ugly:

List<Integer> intList = ...
Integer[] intArray =  intList.toArray(new Integer[0]);

It’s interesting, I never stumbled over this issue before, however I want toArray() to work as expected for generic types and already returning an integer array :/

Adding a Pidgin Trayicon to DWM

December 3, 2009

I am using dwm as a window manager for a long time. I hacked a few things into it which I felt were missing back then when I started to use dwm and got used to it so much that I hesitate to switch to awesome or even a newer version of dwm.

Tiled window managing is really a great idea but conflicts with programs which are design to be used in a more “traditional” desktop environment. One of those application is my instant messenger. I gave up using ncurses based messengers due to their lack of drag’n'drop capabilities, so I started using pidgin.

What I always wanted to have is some kind of tray icon which informs me about new incoming messages. The cool thing about pidgin and the whole underlying purple library is their great support for dbus. So instead of ripping off code from awesome to get full freedesktop compliant tray icons I wrote a small python script to add an icon to my dwm status bar.

The dwm status bar reads a string from stdin (passed to it by xinit) and displays it in the upper right corner of the screen. To do that it uses a loop in .xinitrc like this:

while true
do
	date=`date +'%d.%m.%Y %H:%M'`
	echo $date `pidginProbe.py`
	sleep 3
done | dwm

OK, so I need a script named pidginProbe.py which is just looking for an incoming message on the libpurple dbus interface, prints out a small notification and then terminates.

Here is how I connect to the purple dbus:

bus = dbus.SessionBus()
purple_service = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
purple = dbus.Interface(purple_service, "im.pidgin.purple.PurpleInterface")

Asking for an incoming message is not possible without installing a callback to a ReceivingChatMessage signal. But there is the option to ask for all active conversations which includes open chat windows and newly received messages.

def incomingMessageExists(purple):
    convs = purple.PurpleGetConversations()
    return len(convs) > 0

This function can be used to print [ ] to the screen when no message was received or [M] otherwise.

Of course much more is possible, nearly all important features can be used via dbus. See the developer documentation to find out about the other calls and signals.
I also added a notification which informs me about specific people going online (like my girlfriend ^^), here is the code example (that’s the simple version without error handling):

purple = dbus.Interface...
myid = # my ICQ/Jabber/... account id
contactid = # contact's ICQ/Jabber/... account id
myaccount = purple.PurpleAccountsFind(myid, '')
buddy = purple.PurpleFindBuddies(myaccount, contactid):
if purple.PurpleBuddyIsOnline(buddy[0]) == 1:
    print contactid, "is online"

My Dream Programming Language

November 24, 2009

If one day a fairy would appear in front of me and grant me three wishes, one of them would probably be a new programming language. Here is a list of some features I really want to have in one single language. In a future post I will probably look at some already existing programming languages and examine how much current languages are able to meet my desired features.

  1. Simple & Readable Syntax
  2. Static, Strong Typing & Type-Inference
  3. Functional Programming Support
  4. REPL & Compiler
  5. Easy module/packaging system
  6. Garbage Collection
  7. Immutable Data Types

Read the rest of this entry »


Follow

Get every new post delivered to your Inbox.