Archive for March, 2008

A weekend with Leslie

This weekend, Leslie came down to visit me here at the U of I. Boy, it was blessing to have her here.

She arrived Friday evening, and since we both had had long school days, watching LOST entertained us until bed time. She stayed with my friend Anne at Stratford House, which was certainly very nice of her to do.

Saturday was a day of… walking. Before brunch, we took a walk around the 6-pack and south quad. Then after brunch, we walked up to the Engineering Quad, up a little farther to see my apartment for next year, then all the way down to Oregon Avenue for coffee, and then down past Florida and Lincoln to the Arboretum. For a college in Illinois, the Arboretum was quite pleasant. It had some gardens, a lake, wooded areas, and a Japanese house used by the college for Japanese Education. After we were done with that all, we had to walk back.

In all, Leslie and I walked 7.28 miles, according to Google Earth. You can a trace of our trip below:
Our walk

Today we went to church at TCBC, had brunch at FlatTop Grill (I highly recommend it!), and then plan on spending the rest of our time watching LOST or reading Harry Potter before her bus at 5.

Mandarin Wok: Good Chinese food for a corn field

This evening I went to Mandarin Wok for some chow with my good friend Joey. You know, for being in the middle of a cornfield, the food was actually quite tasty. We ordered off of the Chinese menu, which partially meant that I had no idea what I would be receiving. We pointed to stuff, and in broken English, were told was it was… “Chick-in”, “Veggie-tables”. But whatever it was, it was good.

After the meal, I scurried off to a Computational Theory exam before having to walk the 25 minutes back in the freezing, torrential rains amidst a thunderstorm. A nice warm shower and clean clothes awaited me back at the dorm.

Thread synchronization implementation performance

Thread safety is certainly a very important factor in modern software design, especially as the number of cores increases per machine, and being able to run code concurrently becomes a requirement.

So I decided to see just how expensive using pthread_mutex_lock and semaphores are. The basic test idea is to see how many times you can access a critical section of code. I ran the same test for each synchronization implementation:

  1. No thread-safety.
  2. Thread safe using pthread_mutex_lock.
  3. Thread safe using sem_wait.

The code for each test is below:

void lazy_init_no_lock(void)
{
    static _Bool __isInitialized = 0;
    if (__isInitialized)
        __isInitialized = 1;

    __count++;
}

void lazy_init_lock(void)
{
    static _Bool __isInitialized = 0;

    pthread_mutex_lock(&__lock);
    if (__isInitialized)
        __isInitialized = 1;
    pthread_mutex_unlock(&__lock);

    __count++;
}

void lazy_init_semaphore(void)
{
    static _Bool __isInitialized = 0;

    sem_wait(&sem);
    if (__isInitialized)
        __isInitialized = 1;
    sem_post(&sem);

    __count++;
}

And the results were certainly much more interesting than the code. Pretty much, I called each test from an infinite loop for 5 seconds, and docked how many times I was able to complete the call.

    while(1)
    {
        if (test == 0)
            lazy_init_no_lock();
        else if (test == 1)
            lazy_init_lock();
        else if (test == 2)
            lazy_init_semaphore();
        else
            break;
    }

On average, having no thread safety yielded 440,909,468 calls, thread-safety with mutexes yielded 98,324,839 calls, and semaphores brought up the rear with 1,197,981 calls. It made a nice little graph:
Graph

So I guess the moral of the story is, if you don’t need super powers when doing thread-safety, use mutexes. And if you know your code is not going to run on a multithreaded system, don’t nest all your critical regions in mutexes or semaphores.

How MPRuntime performs

Over spring break, one of the other things I did was do some performance tests of MPRuntime, matching up how it performed against Apple’s Foundation and CoreFoundation frameworks. The results I found were actually quite interesting.

Click here or the button below to see a full report.
View the performance report

Spring Break is over

Last week was my spring break. It was relaxing, a time away from the constant pressure and stress of school and its related activities. Some of the highlights of my break include:

  • Lots of time with Leslie: taking walks, watching LOST, cooking pizza, making pizza blindfolded, and reading Harry Potter to name a few things.
  • Palm Sunday lunch at Grandma and Grandpa’s with the family.
  • Lunch at Thipi Thai in Glen Ellyn with cousins Alli and Emily.
  • Lunch with mom at Sushi House.
  • Picking sister Sarah up from the airport and having breakfast at Egg Harbor.
  • Easter Sunday lunch at Grandma and Grandpa’s with the family.

That was a short list, but it was a good break overall. How do I know? It was hard to come back to school.

Leaving me wanting

The SDK is downloaded, I wrote my first iPhone app, but…

I can’t test it on the iPhone.

Unfortunately, in order to be an iPhone developer, you have to have a certificate that code-signs your software. In order to obtain this certificate, it is necessary to enroll in the iPhone Developer Program, which costs anywhere from $99 to $299. At this point, that isn’t worth it for me.

Conclusion: iPhone development to be continued at a later time.

iPhone SDK on the way

A beta of the iPhone SDK was released this afternoon at about 1 CST. I immediately tried to get on the site, only to be greeted by a friendly page that said:

Safari can’t open the page “http://developer.apple.com/iphone/program/” because the server unexpectedly dropped the connection, which sometimes occurs when the server is busy. You might be able to open the page later.

This continued all afternoon until just about 10 minutes, when I was finally able to get through!
My downloads window

Using counting semaphores on Mac OS X

The POSIX runtime extension includes counting semaphores, specified by functions such as sem_wait, sem_post, and sem_create. Unfortunately, OS X does not implement sem_create for counting (unnamed) semaphores, only implementing it for named semaphores. This certainly creates quite an issue if you want the ease of use (or power in some cases), of a counting semaphore.

I thought I was at a loss for using them until I stumbled upon the Mach kernel primitive semaphores, which happen to be, thank goodness, counting semaphores. The Mach kernel specifies the following functions for using semaphores, as defined by <mach/semaphore.h> and <mach/task.h> (Note: I have only listed the important ones that have POSIX relatives):

kern_return_t semaphore_create(task_t task, semaphore_t *semaphore,
    int policy, int value)
kern_return_t semaphore_signal(semaphore_t semaphore)
kern_return_t semaphore_signal_all(semaphore_t semaphore)
kern_return_t semaphore_wait(semaphore_t semaphore)
kern_return_t semaphore_destroy(task_t task, semaphore_t semaphore)
kern_return_t semaphore_signal_thread(semaphore_t semaphore,
    thread_act_t thread_act)

By looking at them, you can probably guess what they do, and if you don’t, you can always look it up in the documentation, or click here to view it on Apple’s developer website.

You may however, be wondering what the task_t type is, and how you might possibly retrieve the correct task_t struct. But never fear, in <mach/task.h>, there are two methods for getting the current task: current_task and mach_task_self, which both return the current task, but in different forms. For user space programming, you should use mach_task_self, which returns a pointer to the kernel’s virtual memory map. If you are doing kernel programming, however, you would not want to use mach_task_self, and instead you want to use current_task. Do not attempt to use current_task in user-space programming, since linking of your code will fail since the symbol is only available to Kernel extensions.

Below is an example using the counting semaphore primitives. Basically, we are counting up and counting down a static variable by the same amount on two separate threads. With the semaphores, the final value should be zero. If you remove the semaphores, you will not get zero, and you will get some arbitrary value.

#include <stdio.h>
#include <pthread.h>

#include <mach/semaphore.h>
#include <mach/task.h>

static int x = 0;
semaphore_t sem = 0;

void * countUp(void *param)
{
    semaphore_wait(sem);

    unsigned i = 0;
    for (i = 0; i < 100000000; i++)
        x++;

    semaphore_signal(sem);
    return NULL;
}

void * countDown(void * param)
{
    semaphore_wait(sem);
    unsigned i = 0;
    for (i = 0; i < 100000000; i++)
        x--;

    semaphore_signal(sem);
    return NULL;
}

int main (int argc, const char * argv[])
{
    // Create our semaphore. SYNC_POLICY_FIFO is how we handle threads that are
    // waiting on the semaphore. I am pretty sure that POSIX uses FIFO, so I
    // think it is best to use that here, though there are other options defined
    // in .
    int initialValue = 1;
    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, initialValue);

    pthread_t up, down;
    pthread_create(&up, NULL, countUp, NULL);
    pthread_create(&down, NULL, countDown, NULL);

    pthread_join(up, NULL);
    pthread_join(down, NULL);

    printf(”%d\n”, x);  // Should print 0.

    return 0;
}

Now the only problem with this code is that it is not platform independent, and will not compile on Linux. If you wanted, you could make platform independent versions of semaphore creating, posting, and waiting functions, as implemented in the example below:

#ifdef __APPLE__
#include <mach/semaphore.h>
#include <mach/task.h>
#else
#include <semaphore.h>
#endif

void platform_sem_create(void * semStructure, int initialValue)
{
    #ifdef __APPLE__
    semaphore_create(mach_task_self(), (semaphore_t *)semStructure, SYNC_POLICY_FIFO, initialValue);
    #else
    int pshared = 0;
    sem_init((sem_t *)semStructure, pshared, initialValue);
    #endif
}

void platform_sem_signal(void * semStructure)
{
    #ifdef __APPLE__
    semaphore_signal(*((semaphore_t *)semStructure));
    #else
    sem_post((sem_t *)semStructure);
    #endif
}

void platform_sem_wait(void * semStructure)
{
    #ifdef __APPLE__
    semaphore_wait(*((semaphore_t *)semStructure));
    #else
    sem_wait((sem_t *)semStructure);
    #endif
}

Then in your code, just use platform_sem_create, platform_sem_signal, and platform_sem_wait instead of functions like sem_wait, semaphore_create, etc.

And that’s the magic to using counting semaphores on Mac OS X.

Physics done. Forever.

Today at 6:58, I turned in my last physics test for my last physics class ever. It was tremendous. Today was a good day leading up to the test, and it has certainly ended well. I took a few pictures throughout the day to document this momentous occasion, and you can check them out here.

Physics counter.

“It’s coming down to the wire”

The time for the end of physics is drawing near. With no days left, and just a few hours to go, I still don’t feel ready enough to take to the exam. Oh well.

Physics will end in:
Countdown to physics