Phobos threads performance - threadring bench

The Anh Tran trtheanh at gmail.com
Mon Jul 21 14:15:27 PDT 2008


This is my newest threadring.d for the threadring game:
http://shootout.alioth.debian.org/gp4/benchmark.php?test=threadring&lang=all

Need D expert commences. Many thanks.

module ThreadRing;

import std.stdio : writefln;
import std.conv : toInt;

import std.c.linux.pthread;
import std.c.stdlib : exit;

const uint NUM_THREADS = 503;
const uint STACK_SIZE = 16*1024;

int	token = -1;
bool finished = false;

extern (C)
{
	// static array, local data, should be better for L2 cache
	pthread_mutex_t[NUM_THREADS]		mutex;
	// again, local data is better for P4 small L2 cache
	char[STACK_SIZE][NUM_THREADS]	stacks;

	void* thread_func( void *num )
	{
		int thisnode	= cast(int)num;
		int nextnode	= ( thisnode + 1 ) % NUM_THREADS;

		while (true)
		{
			pthread_mutex_lock( &(mutex[ thisnode ]) );

			if ( token > 0 ) // branch prediction as taken
			{
				token--;
				pthread_mutex_unlock( &(mutex[ nextnode ]) );
			}
			else
			{
				 writefln( thisnode +1 );
				 exit(0);
			}
		}

		return null;
	}
}

int main(string[] args)
{
	try
	{
		token = toInt(args[1]);
	}
	catch (Exception e)	
	{
		token = 1000; // test case
	}

	pthread_t cthread;
	pthread_attr_t stack_attr;

	pthread_attr_init(&stack_attr);

	for (int i = 0; i < NUM_THREADS; i++)
	{
		pthread_mutex_init( &(mutex[ i ]), null);
		pthread_mutex_lock( &(mutex[ i ]) );

		// manual set stack space & stack size for each thread
		// stack space is allocated closely together
		pthread_attr_setstack( &stack_attr, &(stacks[i]), STACK_SIZE );

		pthread_create( &cthread, &stack_attr, &thread_func, cast(void*)i );
	}

	// start game
	pthread_mutex_unlock( &(mutex[0]) );

	// wait for result
	pthread_join( cthread, null );

	return 1;
}


More information about the Digitalmars-d-learn mailing list