std.threads : smp programming

Wiz clem.codeur at gmail.com
Tue Jul 31 15:43:15 PDT 2007


std.threads is a great lib, helped me more than one time.
But there was a missing thing, something to really help programmers
making smp code.
We need to create a thread by core/cpu, but, there is nothing like a
function that return the number of processors.
So I googled that, and found in c the get_nprocs function, returning the
  number of available cpus. It's used by including sys/sysinfo.h

Here is a D code that exploits it :


import std.stdio;
import std.thread;
import std.c.time;
import std.math;


extern (C)
{
	//sys/sysinfo.h       info libc --index-search=_SC_NPROCESSORS_CONF
	extern int get_nprocs();
}

class Nb1Calc {
	int increment;
	int number;
	this(int n, int i) {
		increment=i;
		number=n;

		Thread t=new Thread(&calc);
		t.start();
	}
	bool isnb1(int a) {
		int m=cast(int)sqrt(cast(float)a);
		for (int i=2; i<=m; i++)
			if (a%i == 0)
				return false;
		return true;
	}
	int calc() {
		writefln("[Thread 0x", cast(void*)Thread.getThis(), "] Starting thread
(", number, " + x * ", increment, ")");
		for (int i=number; ; i+=increment)
			if (isnb1(i)==true)
				writefln("[Thread 0x", cast(void*)Thread.getThis(), "] Number ", i,
" is a prime number");
		return 0;
	}

}

int main(char[][] args) {
	int ncpu=get_nprocs();
	writefln("Separating in ", ncpu, " threads.");
	for (int i=0; i < ncpu; i++)
		new Nb1Calc((i+1)*2+1, ncpu*2);

        for (;;)
		sleep(2);

	return 0;
}



Determinating prime numbers using each thread by core.
Sorry for using no lock while writefln, it's just an simple example.


Is there a way that get_nprocs could be added in the d's std lib ?
Something like int Thread.get_nprocs(); would be fine.



More information about the Digitalmars-d mailing list