Next Integer, Please

Generating sequential integers is not hard - simple counter++ is enough. Generating sequential positive integers is as trivial if you can use unsigned type. If you must stay in signed world, wrapping everything in condition will do the trick:

if (counter == Int32.MaxValue) {
    counter = 0;
} else {
    counter++;
}

Things get a bit more interesting if you need to do same in thread-safe manner. Obvious (and simplest) solution would be to put code in lock block:

lock (syncRoot) {
    if (counter == Int32.MaxValue) {
        counter = 0;
    } else {
        counter++;
    }
}

That will make code thread safe but it will also make it a lot slower. Every time you take a full blown lock, you will pay a hefty penalty. This example (on my computer) ran more than 30 times slower compared to first solution.

Only if there was an instruction specialized for integer incrementing…

Well, actually there is one - Interlocked.Increment. Unfortunate feature of this function is that (in case of 32-bit integers) once it goes up to 2147483647 it will return -1 as next value. Simple condition is all it takes to make code work:

Interlocked.Increment(ref counter);
if (counter == int.MinValue) { counter = 0; }

Except that this code does not work.

Any condition that touches our variable without being wrapped in some thread-safe construct will make a mess of things. In this case everything will work properly until variable reaches int.MaxValue (2147483647). Step after that we have a race condition between resetting variable to 0 and incrementing it further. If you have it running in two threads maybe it will even work. If code is running in more than that there is high chance you will see number 0 multiple times. Depending on your luck you might even see negative numbers counting up.

Fortunately code can be fixed:

var currCounter = Interlocked.Increment(ref counter);
if (currCounter < 0) { currCounter = currCounter + Int32.MaxValue + 1; }

We leave counter to increment as it wishes. Once it overflows we let it be - it will loop back eventually. However, there is nothing preventing us from modifying returned value because this value is ours alone and no other thread can touch it. We can simply increase all negative value by 2147483648 and we will get nice sequence of [... 2147483646 2147483647 0 1 ...]. Exactly what we wanted. And variable is held “locked” for only one instruction (Interlocked.Increment) so wait between threads is only as long as it needs to be to insure thread-safe operation.

This code is still more about ten times slower than simple non thread-safe example. But it is three times faster than our first go at locking whole operation. Whether this is even needed highly depends on your code. If you increment number only few times, there is nothing really wrong with locking even whole function. Don’t optimize code before you need to.

Timing routines are available for download. Be sure to measure on release code without debugging (Ctrl+F5). Measuring performance on debugging code is worthless because you might detect bottleneck where there isn’t any.

Distribute Me, Scotty

I’ve been waiting long time for this. Visual Studio finally got official support for distributed source control. I personally find it a bit annoying that they opted for Git instead of Mercurial (which is my favorite) but I still like this move. Distributed source control in any flavor is brilliant.

This will not be available out of box until Visual Studio 2012 update 2. However, there is nothing stopping you from manually installing a preview version.

Based on this I think that we can be fairly certain that days of ugly (or non-existent) Windows interfaces for Git are numbered.

PS: I will stick with Mercurial for now - it has great standalone interface and fairly decent plugin for Visual Studio. But I do see myself in future converting few Mercurial repositories to Git just for fun. :)

Curious UART on 16F1516

Lately I have started using PIC16F1516 as my jelly bean PIC. It is cheap, has lot of memory (whooping 512 bytes) and it is fairly well feature-equipped. Best of all, it is almost completely compatible with my old favorite PIC16F1936.

Yes, PIC16F1936 has EEPROM built-in and both feature list and speed are superior. However, not all projects need all features and speed nor is lack of EEPROM something catastrophic.

As always I started programming by copy/pasting old code. Small adjustments were all that was needed. I copy pasted my UART routines and created simple echoing program on chip. And chip stayed quiet.

After some debugging it was obvious that both my timing routines and UART formulas are correct. And code was same as what I used on PIC16F1936:

void uart_init(int desiredBaudRate) {
    TRISC7 = 1; //RX
    TRISC6 = 0; //TX
    SPBRG  = (unsigned char)(_XTAL_FREQ / desiredBaudRate / 16 - 1);
    BRG16  = 0;    //8-bit
    BRGH   = 1;    //high speed
    SYNC   = 0;    //asynchronous mode
    SPEN   = 1;    //serial port enabled
    TXEN   = 1;
    CREN   = 1;
    asm("CLRWDT");
}

In moment of desperation I turned my attention to datasheet. And there, under Asynchronous Transmission Set-up chapter it said “Set the RXx/DTx and TXx/CKx TRIS controls to ‘1’.”

In all other PICs (I had opportunity to play with) TRIS for TX pin either does not matter or you set it to output. For some reason designers of this PIC decided that TX pin needs to be input in order for USART to work. Quite a trap.

Only change that was required was setting TRISC6 to 1 and my board became alive:

void uart_init(int desiredBaudRate) {
    TRISC7 = 1; //RX
    TRISC6 = 1; //TX
    SPBRG  = (unsigned char)(_XTAL_FREQ / desiredBaudRate / 16 - 1);
    BRG16  = 0;    //8-bit
    BRGH   = 1;    //high speed
    SYNC   = 0;    //asynchronous mode
    SPEN   = 1;    //serial port enabled
    TXEN   = 1;
    CREN   = 1;
    asm("CLRWDT");
}

PS: Do not forget to set ANSELC = 0.

Don't Shit in My Flower Pot

Sometime open source drives me crazy.

This time I went about rebuilding TortoiseHg on my machine. I mean, it is a Python program - how hard could it be?

Well, it proved to be more annoying than anything I have done lately. And problems were not in getting code to compile but in getting various dependencies to work properly (py2exe, setuptools, PyQt, pywin32…). While build instructions were better than average open source I was jumping from one problem to another. And most problems were in dependencies incapable of recognizing any folder other than C:\Python27 as python location. Maybe I am misleading a bit here. They would recognize it just fine during install. Everything would fall apart at later time.

Solution was to either rebuild all dependencies causing issues (they were open source them-self) or just to move Python to C:\Python27. As soon I as did latter, everything started magically to work.

For this I only partly blame guys incapable of properly discovering Python location. They suck and they know it. I blame first guy who made Windows port and thought that root folder is a good location as any. Would you install your stuff under root (/) on Linux? How is it that same group of people that behaves properly under Linux has no idea that it should follow same principles under Windows?

P.S. Please don’t tell me that I gave up too easily and that I should have and fixed each issue I encountered. I was attempting to compile one piece of code not solve universes problems.

Mega

Illustration

Since I am now in States and away from my home backup solution, I am always looking into ways to make offsite backup work. My current practice is using WinRAR to compress (and encrypt) important files and then syncing them to cloud via SugarSync.

Since I do backup quite a lot I am nearly always close to not having enough space. That is why I was happy when I heard about Mega. With 50 GB free space I would cover all my backup needs and then some more. So I got my self an account.

It took ages for website to load. Few times I even got up and checked my Internet connection just in off chance that fairies changed it into 28.8k baud modem. Once it finally got loaded I snooped around and noticed that there is no Windows/Linux/Mac/anything client. Relying only on browser upload is a brave decision and, if done right, might not be too ugly until third-party clients arrive.

Biggest annoyance of browser upload if fortunately avoided since there is an option of folder upload. As I uploaded my backup folder I noticed that all files would stay in “pending” state. After few attempts upload did start but speed was maxing at 2 KB. Smallest backup file I got was estimating completion in couple of hours. For 20 MB. And you cannot leave page once upload starts - remember, this is a browser solution.

With this I finish this rather short review of nothing. Because there is actually nothing (other than registering) that I could really test. Site was falling apart even without me doing anything.

Yes, I do know that service is very popular and that is probably reason why it is slow. But frankly I don’t care much. If there is too many users using it, why do they still allow for registration? Wouldn’t it be wiser if they would stop influx of new users until new servers are in place? Or just lock every second account for a few days (with a nice apologetic message). That way at least some people would find service in usable state. Come on guys, you kept Megaupload going. Cannot you float this piece of shit?

I will probably just revisit this in a month or two. In this state Mega might be a nice publicity stunt but as a service it is complete and utter failure.

[2013-01-23: To make things worse, service also seems to be ridden with basic security flaws.]

[2013-01-27: Things do look a bit better now as speed is greatly improved. Although lack of native client still makes whole thing quite annoying for uploads that lack even most basic features (e.g. speed control).]

[2013-01-31: It gets even better. Mega can lose your content on a whim. Nice encourgament to continue using SugarSync.]