The ramblings of a disgruntled geek!!

Tuesday, March 03, 2009

ThreadStaticAttribute

Reminder to self:

ThreadStaticAttribute only works with static fields!

Here is why:

public class TestingTLS
{
    [ThreadStatic]
    public static int value = 0;
    [ThreadStatic]
    public int value2 = 0;   
}

public class MyClass
{
    public static void TLSTest()
    {
        TestingTLS tls = new TestingTLS();
        Dictionary<int, Thread> threads = new Dictionary<int, Thread>();
        Semaphore sem = new Semaphore(100, 100);
        long count = 0;
        for ( int i = 0 ; i < 100 ; i ++ )
        {
            Thread t = new Thread(state => {
                int tid = Thread.CurrentThread.ManagedThreadId;
                TestingTLS.value = tid; 
                Thread.Sleep(0);
                if ( tid != TestingTLS.value )
                {
                    Console.Error.WriteLine( "Value 1: {0} read {1}", tid, TestingTLS.value );
                    Interlocked.Increment(ref count);
                }
                tls.value2 = tid;
                Thread.Sleep(0);
                if ( tid != tls.value2 )
                {
                    Console.Error.WriteLine( "Value 2: {0} read {1}", tid, tls.value2);
                    Interlocked.Increment(ref count);

                }
                threads.Remove(tid);
                if ( threads.Count == 0 )
                    sem.Release();
            });
            threads.Add(t.ManagedThreadId, t);
            sem.WaitOne();
            t.Start();   
        }
        Console.WriteLine("Waiting for all threads to finish...");
        sem.WaitOne();
        Console.WriteLine("Total races: " + count);
    }
}



You will see races for value2 but not for value.

Update: The code snippet was updated, since the previous example had a race where the Total Race count would reach before all threads have finished reporting the wrong number of total races in cases where there were large number of races.

Wednesday, January 28, 2009

First Azure Service is live!



This is my first Azure service that I wrote a couple of weeks ago. It only uses the front end roles and no storage. I will add other applications to this portal, which will use other services offered by Azure.

XmlTextReader fiasco



I hit a snag a few days ago while doing some Xml parsing in one of my applications.

I am using XDocument for Xml parsing(XLinq is beautiful (K)).

Doing XDocument.Load(urlString) or XmlTextReader() would make my application choke with an Xml parsing error (invalid character). Using StreamReader to wrap the actual stream (WebResponse.GetResponseStream) and passing it to XDocument works like a charm. I wrote a sample app to figure out the issue and it turns out that XmlTextReader is the culprit. Maybe it fails to correctly recognize UTF-8 markers, or maybe it's stricter than other Readers, it didn't work for me. So beware. :)

Code Snippet (fails):
WebRequest req = WebRequest.Create("");
WebResponse res = req.GetResponse();
XmlTextReader reader = new XmlTextReader(res.GetResponseStream());
XDocument xdoc = XDocument.Load(reader, LoadOptions.SetLineInfo); //LoadOptions.SetLineInfo helps with debugging.

Code Snippet (works):
WebRequest req = WebRequest.Create("");
WebResponse res = req.GetResponse();
StreamReader reader = new StreamReader(res.GetResponseStream());
XDocument xdoc = XDocument.Load(reader, LoadOptions.SetLineInfo); //LoadOptions.SetLineInfo helps with debugging.


Happy XLinq-ing.

Tuesday, November 25, 2008

A Custom SpinLock based CriticalSection Implementation



Just something I implemented for fun :)


#include "stdafx.h"
#include <intrin.h>
#include <process.h>
#include <vector>
#include <utility>
#include <algorithm>
#include <iostream>
#pragma intrinsic (_InterlockedCompareExchange, _InterlockedExchange)
namespace DotFermion
{
class CCriticalSection
{
enum { LOCK_IS_FREE = 0, LOCK_IS_TAKEN = 1 };
private:
long lock;
long ownerThreadId;
long acquireCount;
public:
CCriticalSection():
lock(LOCK_IS_FREE),ownerThreadId(-1),acquireCount(0){}
~CCriticalSection()
{
Release();
}
//Non-recursive Acquire. Once its called, all threads, even the one owning the lock block on this lock.
//Even a subsequent AcquireRecursive call after this one blocks.
void Acquire()
{
while (_InterlockedExchange(&lock, LOCK_IS_TAKEN) == LOCK_IS_TAKEN);
}
//Recursive Acquire. It doesn't block if called multiple times from the same thread.
void AcquireRecursive(long threadId)
{
if(ownerThreadId != -1 && threadId == ownerThreadId)
{
_InterlockedIncrement(&acquireCount);
return;
}
Acquire ();
_InterlockedExchange(&ownerThreadId, threadId );
_InterlockedIncrement(&acquireCount);
}

void Release()
{
if(acquireCount > 1)
{
_InterlockedDecrement(&acquireCount);
return;
}
_InterlockedExchange(&acquireCount, 0);
_InterlockedExchange(&ownerThreadId, -1);
_InterlockedExchange(&lock, LOCK_IS_FREE);
}
};

}

#define LIST_POS = 4;
#define INDEX_POS = 8;

typedef void (*LPFNTHREADPROC) (void*);
typedef std::vector<uintptr_t> THREADLIST;
typedef THREADLIST* PTHREADLIST;
typedef struct _args_t
{
DotFermion::CCriticalSection* pCs;
PTHREADLIST pThreadList;
int index;
} args_t;

THREADLIST g_ThreadList;
int g_ThreadCount = 0;
int g_SharedCounter = 0;

void ThreadProc(void* argList)
{
args_t* args = (args_t*)argList;
args->pCs->AcquireRecursive((long)args->pThreadList->at(args->index));
g_SharedCounter++;
args->pCs->AcquireRecursive((long)args->pThreadList->at(args->index));
g_SharedCounter++;
args->pCs->Release();
args->pThreadList->at(args->index) = -1L;
g_ThreadCount--;
args->pCs->Release();
delete args;
}

int StartThreads ( int n, PTHREADLIST pThreadList, DotFermion::CCriticalSection* cs )
{
pThreadList->resize(n);
for ( int i = 0 ; i < n ; i ++ )
{
args_t* args = new args_t;
if ( args == NULL ) continue;
args->pCs = cs;
args->pThreadList = pThreadList;
args->index = i;
uintptr_t threadId = _beginthread(ThreadProc, 0, (void*)args);
if ( threadId != -1L )
{
cs->Acquire();
pThreadList->at(i) = threadId;
g_ThreadCount ++;
cs->Release();
}
}
return g_ThreadCount;
}


void Join (int* threadCount)
{
while ( *threadCount );
}

int _tmain(int argc, _TCHAR* argv[])
{
DotFermion::CCriticalSection cs;
StartThreads(100, &g_ThreadList, &cs);
Join(&g_ThreadCount);
std::cout << g_SharedCounter << std::endl;
return 0;
}



Saturday, October 25, 2008

My own GetWsdl tool



I finally figured it out. It was there right in front of my eyes. I stumbled upon it so many times, but I always missed it.

I have been doing web service development for quite some time now. These services are part of pretty complex systems that require a long time to deploy. Imagine, every time there was a build number change and I wanted to modify one of the services. I wrote the code, built it, deployed the services (this step was the longest and most painful), got the wsdl, generated the proxy and updated and built again. The reason it required full redeployment on build number changes is that the assemblies are bound by strong names. It was one heck of a time consuming job. All this work, just to update the proxy; WSDL generation required a live service. :)

Though I still have to do this to verify that the code that I wrote actually works, proxy generation is not that much of a hassle, especially when I am writing code that I know works already and there is minimal need to try it out.

This time has been drastically reduced. Thanks to System.Web.Services.Description.
ServiceDescriptionReflector
.

 

The GetWsdl tool is here. I will publish it soon. Stay tuned.


-UG


Tuesday, October 21, 2008

Update

I haven’t updated my blog for ages. This is a just a refresh post :)

Sunday, November 11, 2007

This is neat



http://scrapzilla.blogspot.com/2007/11/remember-remember_7668.html

A picture (and a good line) is worth a million words.

Update: There was a picture of masks (the ones worn by revolutionaries in Vendetta)  stored inside a fire extinguisher container with a hammer by its side saying, “In case of revolution, break glass”. Below the picture, it says: “And the hammer hangs on”.

Update 2: Here is the original picture :)

v3


Thursday, November 08, 2007

Gra(n)d Finale

This is my first exam as a grad student.

Wednesday, November 07, 2007

The Grand Finale

The finals start from Sunday November 11, 2007. The first quarter has ended. Phew J

Tuesday, May 01, 2007

Fear

Train yourself to let go… of everything you fear to lose.

The fear of loss is the path to the dark side.

Sunday, August 27, 2006

You're a towel!!

You're a beaner towel.

Trying Windows Live Writer (Beta)

This is an awesome product.

Thursday, April 06, 2006

The Microsoft Trilogy

Microsoft ? Me ? No! it cant be like that !! That was the first question I asked for atleast one week when I got up !! It all happened in a snap and I never knew. It all started with a phone interview and the next thing I knew was a congratulations email from Microsoft telling me that I was hired.

It all started like this:

One of my friends sent me an email about Microsoft coming to Dubai to hire Pakistanis. I did not send my CV at first. But then a friend of mine sent his CV, and he got a phone interview. I sent my CV somewhere near the end of January, and got a phone interview in a couple of days. That was unbelievable. It was a lady named Priya, who emailed me and then took my phone interview. That interview was one heck of an experience for me. I thought I had a terrible interview and I never saw myself clearing that one. I got all the technical questions right, but I failed the IQ question. And as I had heard, the IQ question was the decider, which was wrong. In a week I got an email inviting me to Dubai for in-person interviews. This was the beginning of a very long and painful process....

To be continued...

Wednesday, April 05, 2006

http://www.sellsbrothers.com/

This is the home of king of COM, Chris Sells. Also has some stuff related to MS interviews.

http://www.joelonsoftware.com

Home of the founder of FogCreek software and the former Program Manager of the Excel team, Joel Spolsky.

Also see the archive for some interesting articles by Joel.

http://blogs.msdn.com/oldnewthing/

The blog maintained by Raymond Chen, the Windows guru. It has some very interesting articles on Windows history.

I'm a SOFTIE now !!

I am SDE ( Software Design Engineer ) with the OneCare team now.
Oh, I cant believe it yet.

Being high at SOFTEC !!

Come SOFTEC 2006 and it's time to travel to Lahore ( and get high !! ).
We had an awesome third position at SOFTEC 2005, so it was like this time, we were expected to win, or else get our asses whacked.

And guess what ? We won SOFTEC 2006 !!

One heck of a year!

Man !! That could keep me going for years !!

T.E. at NED was a mess. I did all sorts of things, except studies, which I hated ( my transcript makes this more visible, if you are not convinced ).

The first new great thing that I explored was going to programming competitions. Man !! That was awesome. We had three competitions, and we were like fourth, third and second, in the first, second and third competitions. So it was quite an improvement.

I had a great unexpected win in a software competition also !


BILL !! You gotta come up with a better pickup line, or else, asking her SAT score is definitely not going to do it.


I did a couple of nice projects, wrote a couple of paper-like things, enjoyed hanging around with friends after school, and getting high ( not literally ;) ) !!

Exams ? What are you talking about ? I'm high !!

Microsoft Interviews in May !

Microsoft will be interviewing candidates from Pakistan in May. Post your CVs to pakcv@microsoft.com

Soon Microsoft will be interviewing interested and qualified candidates from Pakistan for software development positions here in the USA at our corporate headquarters working on our major products.

If you know of anyone that might be interested, or a bulletin board where it would be appropriate to post this, please forward this email. There are multiple positions open and candidates will be in competition with themselves, not each other.

What is a qualified candidate?
* Someone who has (or will be completing this year) a bachelor’s (four year or more) degree in Computer Science or a related field
* Someone that has very strong abilities to write code in C/C++
* Someone that is very driven and passionate about technology, desiring to make software products that will go all over the world
* Someone with fluent English speaking skills

WHATEVER YOU DO, DO IT AT MICROSOFT
The reason so many people from various disciplines come to Microsoft is because we provide the most exciting challenges in the industry. Since our inception in 1975, Microsoft’s mission has been to create software for the personal computer that empowers and enriches people in the workplace, at school and at home. Microsoft’s early vision of a computer on every desk and in every home is coupled today with a strong commitment to Internet -related technologies that expand the power and reach of the PC and its users. You can help shape the industry in nearly countless ways, all while gaining invaluable experience. Our casual environment lends itself to freer thinking and therefore, creative problem-solving. However, the coolest part of all is the diversity of jobs. You’re guaranteed not to be bored.

We invite you to join us as we move toward the .NET age, the next generation of our products. You could create a world of change in one of these pivotal, Redmond, Washington USA area positions in the Microsoft product groups. Here is a list of the core positions we will be looking to fill.

Software Design Engineer in Development
Design and implement various new components of the next release of the Windows operating system, Office, Visual Studio, .NET, MSN, SQL Server or other key Microsoft Products. Specific areas of expertise include COM/DCOM, ActiveX, Java, Graphics, Networking, and Base/Kernel. The candidate should have BS or MS in Computer Science, Computer Engineering, Informatics, Physics or Mathematics. Strong C/C++ skills, sound knowledge of operating system fundamentals and server development, and preferably more than 3 years of programming experience.

Software Design Engineer in Test
Design and develop test plans/test suites to test various components of one of our primary products- Windows , Office, Visual Studio, .NET, etc. Work closely with the developers and other test team members to isolate and resolve problems. The candidate should have BS or MS in Computer Science, Computer Engineering, Informatics, Physics or Mathematics. Strong C/C++ skills, sound knowledge of operating system fundamentals and server development and preferably more than 3 years of programming experience.

There are multiple positions open, so please share the information with someone as good as you are.

All positions are at our corporate headquarters in Redmond, Washington, USA. We do require functional level English language skills, written and spoken.

If you are interested, please email your CV in English to pakcv@microsoft.com

Microsoft is an equal opportunity employer.

Keyboard

Keyboard
Keyboard

Blog Reading Level

blog readability test
Powered By Blogger

VerveEarth