Tuesday, September 20, 2011

MyThread threading library project

My first project in my Master's studies proved to be challenging. It was Operating Systems project under professor Vincent Freeh. I was asked to create a new user-level threading library in C for unix-based operating systems which can be made use of to create multi-threading programs (well, an abstraction of multi-threading). Apart from threading, the library also provides for mutual exclusion of threads through semaphore handling. The following is the description of the functions the library provides (courtesy: Prof Vincent Freeh)

Thread routines

MyThread MyThreadCreate (void(*start_funct)(void *), void *args);

void MyThreadYield(void);

int MyThreadJoin(MyThread thread);

void MyThreadJoinAll(void);

void MyThreadExit(void);

Semaphore routines:

MySemaphore MySemaphoreInit(int initialValue);

void MySemaphoreSignal(MySemaphore sem);

void MySemaphoreWait(MySemaphore sem);

int MySemaphoreDestroy(MySemaphore sem);

There are two other unix process routines which are similar to the above functions. So it's like we can create multiple threads using a call to MyThreadCreate(), which may in turn create several threads, make a thread wait for other threads to finish and so on. Though it sounds simple now, threading is more than calling the specified function. We should be able to switch between the threads, save and resume them exactly from where they were left and such complexities arise. This is where we make use of the unix system calls to makecontext(), swapcontext(2), getcontext(1) and setcontext(1). I abstracted the threads using a structure, which saves its context and other details like thread id etc and save them. Whenever a call to one of the library routines is made, the corresponding thread variable is found, and its context is updated properly and switch context with another thread if needed.

This was a very useful project for me to learn about threading, pointers (a lot actually) and unix operating system. Though the library I created is for educational purposes and not intended for production use, a variety of threading programs can be written for this library and most of them work well. This project is not complete and there are a few minor bugs with memory management. I'd be happy if the bugs are pointed out.

Download the code for the project here.

No comments:

Post a Comment