Category Archives: C#

Zencomic 0.2.1 : OH HAI!

After fighting a bit with Gtk# widget styling and MonoDevelop tarball deployment, here is a new Zencomic.

Summary

Zencomic is the comic strip-driven productivity enhancer that periodically makes your day funnier by showing comic like Dilbert or XKCD in a bubble.

What’s new aka The Cool Stuff ™

New, window-based, popup

Tired of having some comic showing far too small ? This is for you !

Now, if you go to the preference dialog, you will be able to switch to a window-based popup which shows your comics in all their greatness at the expense of taking more window space and making your boss, who was incidentally passing by, angry at you (in that case, a quick click on the popup will close it).

new-window-popup

Can I haz lolcats ?

Lolcat greatness is here with the addition of a new addin :

zencomic-lolcat

The remaining

  • For the Gnome Do junkie, Zencomic now correctly comes with a .desktop file so that you can launch it from there
  • Made the preference dialog show in a little saner way i.e. by coming up directly at the front (which apparently wasn’t the case with some WM).
  • The traditional round of bugfixes (should you still spot one don’t hesitate to manifest in the comments)

Downloadz

Tarball : http://netherilshade.free.fr/mono/zencomic-0.2.1.tar.gz

If by any chance you feel this is an application that should come in your distribution, don’t hesitate to contribute some packages ;-) .

GSoC: the now and the next

As you may recall, I have the great pleasure to participate again in Google Summer of Code this year with Mono.

Since we are nearing midterm evaluation, I thought about doing a kind of status report like last year. Unfortunately, I haven’t been as active as I wanted to this time (exams were more time consuming this semester). However there is still some cool stuff that have already landed and which are described next.

What has been done since last year

Actors and Software-transactional-memory goodness

I took some time to implement rudimentary version of those two parallel programming paradigms earlier this year.

See this post which describes in more details the ideas behind them and some examples.

New more efficient scheduler’s deque

The scheduler’s deque that was used before was quite complex due to the fact that the inherent storage mechanism was based on a doubly linked-list which is rather hard to get right when you add parallel and concurrency constraints (see ABA problem for instance).

The algorithm I was using was mostly designed with C++ in mind where you can mess up with pointers pretty easily and make freely use of CAS on pointers as integers. Since I wanted to avoid any kind of unsafe or native code in the library, I tried to port that algorithm down to C#.

After some mail exchange with a fellow person (hey Susan o/) who was using Mono’s ParallelFx on a big box in a laboratory, we started to see some concurrency problems with my code. Turns out that the ABA prevention code wasn’t really working with my C# rewrite. Therefore I decided to hunt for another, more C#-friendly, type of scheduler’s deque.

Actually, I did find it and it’s the one used now under the CyclicDeque name. It’s particularly swift because it only do integer manipulations that are particularly fast with the C# Interlocked methods and doesn’t suffer of the ABA problem because, using the vast range of values available with 64 bits integers, it’s based on a forward-only algorithm.

With the tests I was able to do, this new deque works more reliably and faster than the precedent. It’s currently enabled by default but I need to do some 32 bits checks to see if it behaves as expected on those plateforms.

New types

Following the new type introduced as part of my first SoC and the two parallel paradigms I described above, I have done some other parallel and concurrent code to be used both internally and publicly.

One of those is a new collection, ConcurrentSkipList that provides a thread-safe implementation of a skip-list (a nice tree-ish list container). This skip-list implementation is also used for the ConcurrentDictionary type.

The other is a stripped down CountdownEvent called Snzi (Scalable non-zero indicator) that basically do the same thing except that instead of keeping a count record, Snzi just tells in a binary fashion if there is or not a count remaining. That weaker semantic opens the door for more scalable and efficient optimizations.

Optimizing, fixing and hardening

The final task that occupied me during the inter-soc period was mostly tuning and bug-fixing the existing parts with a focus on Task reliability and PLinq performance and correctness.

What have I begin to do for this SoC

Currently I’m hard working on the .NET 4 port of Mono’s ParallelFx as it comes with a whole lot of new stuff and API changes.

The ParallelFx team over at Microsot has been publishing posts these last months about the new things coming down the pipe (check out their blog if you still haven’t do so).

At the moment, the System.Threading.Tasks namespace port is fairly complete and Tasks/Future unit tests are all back to green.

I’m now working a bit on the Collections namespace, adapting some of my code to the new API (notably ConcurrentDictionary) and seeing how to implement the new Partitioner pattern.

What to expect next

mono-ireland

First of all, the following weeks are going to be quite more productive as, with big thanks to Alan and Miguel, I’m going to spend a month in Dublin hacking in the Novell offices. Looking forward to this.

As for the next, the plan is to continue porting the existing code to .NET 4, first with the Parallel loops class (with probably some further optimizations on data source partitioning) and then PLinq.

In addition, since Mono recently enabled the .NET 4 profile in SVN, some of the ParallelFx code will also soon transition from the google code repository to official Mono’s trunk for early mass consumption.

Finally, last but not least, I’m going to devote the rest of the summer to testing ParallelFx more extensively with, both, improving the existing test suite with harder parallel stress-testing and the development of a Chess-like parallel correctness checker.

See you at the end of the SoC for another full report ;-) .

MD quick feature : switch support in Autotools deployment project

Just to let you know that MonoDevelop’s Autotools deployment projects now allow you to add specific switch for the configure script.

Let’s say for instance that you want to enable at compile time a specific feature in your project. Now what you can do is add a switch to your deployment project which will be turned in something like --enable-super-feature on configure side (i.e. you will be able to run configure like ./configure --enable-super-feature).

This will actually define (as in #define) a symbol that you can use with #if … #endif constructs in your code to activate your specific feature.

Since we are at it, here is a little screenie :

md-switch-defines

I will add support asap for simple makefile projects. The UI is also probably a bit rough, if there are any usability expert out of there I will gladly accept any sensible criticism :-) .

Zencomic 0.1.3

This is a release that was lying around on my desk. It contains a little set of new features.

Summary

Zencomic is the comic strip-driven productivity enhancer that periodically makes your day funnier by showing comic like Dilbert or XKCD in a bubble.

ChangeLog

  • Added a ‘Show now’ button for immediate pleasure consumption
  • Image processing is now deferred to a separate thread
  • Tentatively try to see if the screensaver is active

Download

Tarball : http://netherilshade.free.fr/mono/zencomic-0.1.3.tar.gz

Enjoy !

Zencomic 0.1.2

Edit: And two releases in the same day. Thanks to goto for discovering the CPU issue.

A bunch of fix and improvements for Zencomic, the comic strip-driven productivity enhancer.

Changelog

  • Fix CPU usage bug
  • Geekscottes addin contributed by Frederic Forjan
  • Added conditional compiling for Timeout.AddSeconds (--enable-timeout-second switch). Fix build error for non-svn Gtk#
  • Intercept SIGINT and SIGTERM signals to save configuration before exiting
  • Added COPYING file

Tarball : http://netherilshade.free.fr/mono/zencomic-0.1.2.tar.gz

Mathematical digression : Buffon's needle

Buffon’s needle is a statistic experiment created by Comte George-Louis Leclerc (sounds so frenchie).

The principle is to drop needles on a parquet floor and check if the needle cross one of the parquet line (providing each parquet’s strip has the same height).

The experiment can be modeled as two random variables representing, for the first, the distance between the center of the needle and the closest parquet line, for the second, the acute angle between the needle and the line. Both random variables follow an uniform distribution, respectively of parameters (0, {\frac{length(needle)}{2}} ) and parameters (0, {\frac{\pi}{2}} ).

A needle cross a line when the angle is superior to 0 and, depending on the previous angle, the distance is less than :

{sin(angle)\times\frac{height(strip)}{2}}

Thus, the condition “the needle cross the line” can be summarized by this equation :

{x \leq \frac{l}{2} \sin (\theta)}

Where a is the length of the needle, θ the angle and x the distance.

The cool part is that computing the joint probability of the two random variable with the crossing condition gives you an expression of π :

{\pi = \frac{2aN}{ln}}

Where N is the number of needle dropped, l the height of a strip and n the number of needle that crossed the line.

Therefore, for a good number of needle drop you can get a value fairly close to π.

The following C# source code is doing precisely that :

Which give us a rather good approximate of : {\pi \approx 3,14208745948547}

Because useless is always a must-have

If you are a webcomic fan like me and wouldn’t mind a strip from time to time disturbing a little your workflow, here is a little application I wrote up that might interest you.

I called it Zencomic. It simply displays a notification bubble with a random comic regularly. Everything is implemented as addins via Mono.Addins and currently you have a Dilbert addin and an xkcd addin coming with for free.

Screenie :

zencomic-screen

Tarball : http://netherilshade.free.fr/mono/zencomic-0.1.tar.gz

Yet another round of Summer love

2009-summer-of-code-logo-final-r3-01

This year again, I will have the pleasure to participate in GSoc, continuing my work on ParallelFx with the Mono folks. Yay !

Basically, my three main tasks will be :

  1. Port the code over the new ParallelFx API which is coming in the .NET 4 framework beta
  2. Improve the testing and reliability of the library
  3. Integrate all that stuff into Mono trunk for widespread consumption

You can find the summary of my proposition on the GSoC website.

In other news, I opened an identi.ca account where I will report my progress over the summer among other stuff. Check it out at : http://identi.ca/garuma/all

DBus-Explorer 0.5

Time for another release of DBus-Explorer, your favorite D-Bus API viewer.

Summary

D-Bus Explorer is a GTK+ application written in C# which use NDesk’s managed D-Bus library to display the API of D-Bus services. In summary, it’s a clone of dbus-viewer with a GTK+ interface.

New in this release

  • UI cleanup. Interface generation is now only available when right clicking interface item and allow to select items individually :

    2009-03-23-092546_647x631_scrot

  • Method invoking for simple methods (i.e. only when base type are involved in the method prototype) :

    2009-03-23-092916_404x207_scrot

  • Property support is back :

    2009-03-23-093007_802x625_scrot

  • Yet another parser rewrite. This time it’s definitely cool.

Download

Tarball : http://www.ndesk.org/archive/dbus-explorer/dbus-explorer-0.5.tar.gz

Future

For my usage, D-Bus Explorer is starting to get rather feature complete. Therefore, if you have any idea of a cool feature that could be implemented don’t hesitate to drop your thought in the comments.

Exploring other concurrency models

So, as you know ParallelFx helps programmers getting their software working nicely with multi core systems. To that end, it gives you several way to parallelize your code.

Nowadays in ParallelFx

The most simple and barebone approach is the Task API which is more or less a transcription of the standard .NET threading API (with some cool twist like continuations). Contrary to the ThreadPool or standard Thread, Tasks try to alleviate the work of the OS scheduler by using the ideal amount of workers. Thanks to that, thread context switches are avoided and it allows to get the more out of your processor cores in term of parallelism.

Closely building on that part, you have another nice abstraction called futures which let you think in term of computations rather than acting on results. Indeed, instead of directly manipulating results (and incidentally being bound by their computing time) you are encouraged to express how you would chain up result manipulation together and actually let the thing computes itself when it is really needed. That way, it allows everything to be done in background and be returned when ready.

Then, there are the Parallel class constructs that mimics classical imperative loops among which you find For, ForEach, While, etc. This way, imperative programmers feels at home and can get their loops parallelized easily (supposing there are no nasty side-effects and unprotected shared state manipulations of course).

Finally, PLinq allows query fans to get their Linq expressions running in parallel. Again, provided that there are the same conditions of thread-safety, this layer allows quick migration of existing code (basically some s/Enumerable/ParallelEnumerable/ and the addition of AsParallel() operator).

The Big Picture

The realization that starts to arise from the current work done on parallel system (especially those applied in imperative language) is that shared state is evil.

The problem with shared-state is that it inherently hurt down parallel performances. When using lock for instance, you prevent your code from scaling when the number of processor core increase as you waste CPU cycle to spin waiting for the locked resource to be freed (locked operations are also flawed in the sense that they can’t be composed together but that’s another subject).

Atomic primitives, like CAS, aren’t a panacea either as they perturb the caching mechanism of the CPU (forcing cores to flush their internal cache and go back fetching the new values) thus bringing poorer performances.

All in one, there is no miracle solution to this problem. It’s a consensus that we still have to maintain a certain amount of sharing mechanism cause doing a completely “pure” software with no side effects or mutation is either awkward or abnormal for the usual imperative programmer.

In fact there is an existing “solution” but it’s rather extreme : isolation. In a perfect world, all your parallel task would work on their stuff in a completely isolated fashion with walls around the task to prevent any kind of cross-thread access. That way no lock, no cache messing, etc can get in the way. Utopia he ?

Today in Mono.Threading.Extensions

Inheriting from the previous conclusions, there is an interest today in creating hybrid systems where isolation is the default while still allowing from time to time communication between each isolation domains.

At the moment, the two most popular in my sense are actors (popularized by Erlang) and software-transactional-memory.

The former rely on message passing between independent object to achieve concurrency while the latter works like a MCC database where each thread acts on its own copy of objects with the changes going back later on in the shared memory and in a transactional manner.

Brainstorming on these ideas, I implemented really simple version of the two mentioned systems, both relying on existing ParallelFx components.

Actors

My actor implementation uses the Task API and the existing work-stealing scheduler. To allow some sort of preemptive scheduling (and thus avoid deadlock when actors are waiting for message from another actor) some operation are abstracted through combinator methods like Loop, LoopWhile, AndThen, etc…

Following is an example of a process ring using 10 000 actors each passing around a message token to its neighbor seven times :

using System;
using System.Threading;
using Mono.Threading.Actors;

namespace ActorTest
{
  class Process
  {
	IActor actor;
	int round = 0;
	int id = sharedId++;

	const int MaxRound = 7;
	static int sharedId = 0;

	public Process(Func<Process> next)
	{
	  actor = Actor.Create (() => {
		  Combinators.Loop (() => {
			  if (actor.Receive ((m) => next().actor.Send(null, m.Message))) {
				round++;
				if (id % 10 == 0)
				  Console.WriteLine(id.ToString() + " : " + round.ToString ());
			  }
			  if (round > MaxRound) {
				Console.WriteLine("Finish");
				Environment.Exit (0);
			  }
			});
		});
	}

	public void Start()
	{
	  Console.WriteLine("Starting");
	  actor.Send(null, MessageArgs.Empty);
	}
  }

  public class MainClass
  {
	static Process mainProc;

	public static void Main()
	{
	  InitProcess(0);
	  mainProc.Start();
	  Thread.Sleep(50000);
	}

	static Process InitProcess(int count)
	{
	  if (count == 10000)
		return new Process(() => mainProc);
	  if (count > 0) {
		Process temp = InitProcess(count + 1);
		return new Process(() => temp);
	  }

	  Process tmp = InitProcess(count + 1);
	  mainProc = new Process(() => tmp);
	  return null;
	}
  }
}

While there are 10 000 actors here, only two threads are doing the actual processing on my dual-core system.

STM

The software-transactional-memory implementation manage copies of the shared objects that are passed to the transaction and later on uses MCas (multi compare-and-swap) to update the shared locations. MCas is itself based on an almost wait-free algorithm where threads try to cooperate rather than wait idly.

Again following is an example of transaction showing the traditional bank account problem with concurrent deposit/withdraw operations :

using System;
using System.Threading;
using System.Threading.Tasks;

using Mono.Threading.Transactions;

namespace StmTests
{
  public class StmTest
  {
	const int NbTimes = 100;

	class BankAccount : ICloneable
	{
	  int amount;

	  public BankAccount (int amount)
		{
		  this.amount = amount;
		}

	  public int Amount {
		get {
		  return amount;
		} set {
		  amount = value;
		}
	  }

	  public object Clone ()
	  {
		return new BankAccount(amount);
	  }
	}

	StmObject<BankAccount> amount =
	  new StmObject<BankAccount> (new BankAccount (100));

	public void Withdrawn (int number)
	{
	  Transaction.Create(OpeningMode.Write, amount, (acc) => {
		  acc.Amount -= number;
		}).Execute();
	  // Simulate activity
	  Thread.Sleep(0);
	  Console.WriteLine("Removed {0}€", number);
	}

	public void Deposit (int number)
	{
	  Transaction.Create(OpeningMode.Write, amount, (acc) => {
		  acc.Amount += number;
		}).Execute();
	  // Simulate activity
	  Thread.Sleep(0);
	  Console.WriteLine("Added {0}€", number);
	}

	public int Amount {
	  get {
		return amount.Value.Amount;
	  }
	}

	public static void Main ()
	{
	  StmTest test = new StmTest();

	  Console.WriteLine ("Base amount : " + test.Amount);

	  Task t1 = Task.StartNew(_ => Repeat ((o) => test.Withdrawn (5)));
	  Task t2 = Task.StartNew(_ => Repeat ((o) => test.Deposit (5)));

	  Task.WaitAll (t1, t2);

	  Console.WriteLine ("Final amount : " + test.Amount);
	}

	static void Repeat (Action<object> action)
	{
	  for (int i = 0; i < NbTimes; i++) {
		Task.StartNew (action);
	  }
	}
  }
}

The Future

The parallel team at Microsoft is already working some of the stuff I described above for inclusion in ParallelFx. The STM group now has its own blog and there are experimentations going on in concurrency-friendly DSL.

You may find yet more exciting stuff of what is brainstormed in this video of Joe Duffy and Erik Meijer.

Conclusion

Thoughts ? Comments ? Use cases sharing ? You can go wild in the comments ;-) .