A Developer's Diary

Feb 9, 2011

Thread Synchronization in Windows using Critical Section

In multi threaded environments, where more than one thread operates on the shared data (global variables, collections) the results can be unpredictable due to race conditions. Critical Section is a mechanism that ensures that only one thread executes a particular piece of the code. A thread, once it enters a critical section should not be interrupted. Critical Sections have the advantage of not being kernel objects and are maintained in user space. This usually, but not always, provides performance improvements. The CRITICAL_SECTION data type is basically a structure whose fields are used only internally to Windows

Windows provide four functions for using critical sections. To use these functions, you must define an object of type CRITICAL_SECTION.

Key Points

1. Define a CRITICAL_SECTION object cs
2. Initialize a Critical section using InitializeCriticalSection (&cs);
3. After the critical section object has been initialized, a thread enters the critical section by calling EnterCriticalSection(&cs); No two threads can own the critical section at the same time
4. A thread leaves the critical section by calling LeaveCriticalSection (&cs);
5. When the critical section object is no longer needed, it can be deleted by the program by calling DeleteCriticalSection (&cs);
#ifndef _Lock_H_
#define _Lock_H_

#include <windows.h>

/**
*@description: A simple Lock implementation using windows critical section object
*/

namespace examples
{
    class Lock
    {
    public:
        Lock()
        {
            ::InitializeCriticalSection(&m_cs);
        }

        ~Lock()
        {
            ::DeleteCriticalSection(&m_cs);
        }

        void acquire()
        {
            ::EnterCriticalSection(&m_cs);
        }

        void release()
        {
            ::LeaveCriticalSection(&m_cs);
        }

    private:
        Lock(const Lock&);
        Lock& operator=(const Lock&);

        CRITICAL_SECTION m_cs;
    };

}

#endif //_Lock_H_


Read more ...

Feb 2, 2011

Multithreading in Windows - A simple example

A thread is an independent unit of execution within a process. Threads under windows can be created/terminated using the following Win API functions:

1. CreateThread()/ExitThread() system calls.
2. _beginthread()/_endthread() OR _beginthreadex()/_endthreadex() CRT functions.

Key Points

1. Using CreateThread() in a program that uses the CRT functions (for example, links with LIBCMT.LIB) may cause a memory leak of about 70-80 bytes each time a thread is terminated.
2. _beginthread()/_endthread() CRT functions provide a simpler interface but should be avoided. _beginthread() does not have a security attribute, and does not return a thread id. More importantly, it closes the handle of the thread it creates, and the returned thread handle may be invalid by the time the parent thread stores it. If the thread spawned by _beginthread() exits quickly, the handle returned to the caller of _beginthread() may be invalid or, worse, point to another thread. Also avoid _endthread() it does not allow for a return value.
3. With _beginthreadex(), you can use security information, set the initial state of the thread (running or suspended), and get the thread identifier of the newly created thread. You are also able to use the thread handle returned by _beginthreadex() with the synchronization APIs.
4. _endthread() or _endthreadex() is called automatically when the thread returns from the routine passed as a parameter

The example code creates three independent threads using _beginthreadex() in suspended state scheduled to run for 10, 20 & 30 seconds. The threads resume execution after the call to ResumeThread(). The WaitForSingleObject() waits for the given thread for passed slice of time. The function returns with value 0 if the thread terminates by self and by value 258 if a thread's execution is timed out

Read more ...

Jan 31, 2011

Overloading operator()

Browsing through some of the open source code implementation in C++, came across the function void operator()()
Q. Why would one use operator() in the first place?
A. Simplicity of usage. Of course, less intuitive if you are seeing it's use for the very first time.

The program below implements a matrix and uses operator() as a replacement of subscript operator[] to retrieve and set values at the particular location.

#include <iostream>

//File: Matrix.h

class Matrix
{
public:
    Matrix(size_t rows, size_t cols);
    Matrix(const Matrix &m);
    virtual ~Matrix();

    Matrix& operator=(const Matrix &m);
    double& operator()(size_t row, size_t col);
    //double operator()(size_t row, size_t col) const;

    size_t getRows() const;
    size_t getCols() const;

private:
    Matrix();
    void copy(const Matrix &m);
    void init(double value);

    size_t _nrows, _ncols, _size;
    double *_data;
};

Excercise
Why is the method commented out in the above code?
//double operator()(size_t row, size_t col) const;

Read more ...

Jan 23, 2011

C Program - struct usage example

This is a follow up post on my last blog update Pointers in C - an eye opener. The program touches on the following -
1. Using struct as Employee record
2. Using pointer to Employee* as an employee list
3. Using void pointer and casting it to an appropriate type to avoid duplicate code
4. Allocating memory and freeing memory

struct Person
{
    char *name;
    size_t age;
};
typedef struct Person Employee;

struct Organization
{
    Employee **emplist;
};
typedef struct Organization Org;

A sample execution of the program should be as shown:


Read more ...

Jan 20, 2011

Pointers in C - an eye opener

My friend once asked me a problem in C involving struct and pointers. I was confident that the solution I had proposed would work untill I finally gave it a try.
Among the common mistakes i could not avoid were not allocating memory before trying to use the pointers and trying to dereference a pointer as p->q->*num :)

#include <stdio.h>

struct B
{
    char *str;
    int  *num;
};

struct A
{
    struct B *q;
};

int main()
{
    char *tstr = "Hello World";

    /**
     * 1. The program should copy the value tstr in str and print it
     * 2. The program should assign value 100 to num and print it 
     */
    struct A *p;
}

Read more ...