One Thread per Class

Java’s thread class enforces an interesting pattern and an opportunity to practice the principles of affinity and separation of concerns. Quoting the thread class’ documentation:

Declare a class to be a subclass of Thread. This subclass should override the 
run method of class Thread. An instance of the subclass can then be allocated 
and started. 

For example, a thread that computes primes larger than a stated 
value could be written as follows:

class PrimeThread extends Thread {
         long minPrime;
         PrimeThread(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }

Essentially, a thread must be a class and conversely a class may have no more than one thread.  An argument in favor of one thread per class is a higher likelihood that all of the thread’s operating data is in the class (fairly trivial), and conversely data in the class is closely correlated with its single thread. In the example above, calling start() on a PrimeThread object instance will compute primes larger than the seed prime (minPrime).

Compare Java’s threading with  C++ or C# where threads are methods. A C++ class that spawns two or more threads will contain data for each thread; e.g. state information, signals and events etc., leading to code that is harder to extend, test and maintain. Here’s a C++ version of PrimeThread that uses _beginthread:

class PrimeThread
{
private:
	long   mMinPrime;
	HANDLE mThread;
public:
	PrimeThread(long minPrime) :
	  mMinPrime(minPrime),
	  mThread( ( HANDLE ) _beginthreadex(0, 0,
 &PrimeThread::run0, this, CREATE_SUSPENDED, 0) )
	{
		//check for invalid mThread
	}

	PrimeThread::~PrimeThread( )
	{
		if ( mThread )
		{
			CloseHandle(mThread);
		}
	}

	void start( )
	{
		ResumeThread(mThread);
	}

	static unsigned PrimeThread::run0(void *p)
	{
		if ( !p )
		{
			return 0;
		}

		auto me = (PrimeThread *) p;
		me->run( );
		return 0;
	}

	void run( )
	{
		// compute primes larger than minPrime
		...
	}
};

Calling start() on a PrimeThread instance will cause the class’ run() function to run in a new thread, much like its Java counterpart. It is quite straightforward though, to add a new thread object to the class, and have that thread perform alternate tasks on alternate data, increasing the class’ complexity.

A C++ class that  encourages the “one thread per class” rule can be declared as:

class Thread 
{
public:
	Thread();
	~Thread();

	void start() ;
	virtual void run() = 0;
	void yield();
	void join(long timeout = -1);
	void interrupt();
 static void sleep(long millis);
 // other threading functions ...
};

We can rewrite PrimeThread as:

class PrimeThread : public Thread 
{
private:
	long minPrime;

public:
	PrimeThread(long minPrime) 
	{
		this->minPrime = minPrime;
	}

	void run() 
	{
		// compute primes larger than minPrime
		. . .
	}
};

Since PrimeThread inherits from Thread, calling start() on an instance of PrimeThread is all that’s needed. If we insist that all threads must inherit from the Thread class, we’re naturally prevented from more than one thread per class.

When used with a callable object, Boost’s thread class imposes a similar constraint. However we’re left with managing two objects.

class PrimeThread 
{
private:
	long minPrime;

public:
	PrimeThread(long minPrime) 
	{
		this->minPrime = minPrime;
	}

	void operator()() 
	{
		// compute primes larger than minPrime
		. . .
	}
};

//create a boost::thread object (set to autorun)
boost::thread t1(PrimeThread(1));

Integrating uncrustify into Visual Studio

I like clean code and I cannot lie. Visual Studio’s native code formatter is quite basic — it indents code, but doesn’t clean up spacing etc. While the Resharper extension does a great job for C#, there isn’t a good integrated tool for VC++.

Uncrustify is a command line tool that does a remarkable job on C / C++ and other languages. Running it from a command prompt (or even as an external tool) can get tedious rather quickly. At RemoteReality, we use a VS macro to launder code through uncrustify with a single keyboard shortcut.

    Sub Uncrustify()
        Dim proc As New System.Diagnostics.Process()

        If (DTE.ActiveDocument IsNot Nothing) Then
            Dim doc As Document = DTE.ActiveDocument.Object("Document")
            Dim procStart As New System.Diagnostics.ProcessStartInfo()
            Dim outputFile As String = doc.FullName + ".uncrustify"

            procStart.Arguments = "-c \rrdeV\Vperi\repos\unCrustify\rr.cfg -o " + outputFile + " -f " + doc.FullName
            procStart.FileName = "C:\Program Files\uncrustify\uncrustify.exe"
            procStart.CreateNoWindow = False
            Diagnostics.Process.Start(procStart).WaitForExit()

            Dim txt As TextDocument = DTE.ActiveDocument.Object("TextDocument")
            Dim ep As EditPoint = txt.StartPoint.CreateEditPoint

            ep.EndOfDocument()
            Dim endPoint As TextPoint = ep

            Dim sp As EditPoint = txt.StartPoint.CreateEditPoint
            sp.Delete(endPoint)
            sp.InsertFromFile(outputFile)
            System.IO.File.Delete(outputFile)

        End If
    End Sub

The macro runs uncrustify on the document currently active in the editor and sends the formatted output to a temporary file. It deletes the text in the editor and replaces it text from the generated file.

The macro and our favorite configuration files can be found here.