Threading

Steven Schveighoffer schveiguy at yahoo.com
Tue May 12 05:13:11 PDT 2009


On Tue, 12 May 2009 05:11:49 -0400, Brok3n Halo <x2ndshadow at hotmail.com>  
wrote:

> I probably should have phrased my question better with the array, what I  
> was
> wondering is if it was safe for say two threads to right to the array at  
> the same
> time as long as I'm sure they're not writing to the same index of the  
> array?

You can do anything you want without thread safety, but you run the risk  
of deadlocks or corrupted memory.

The problem isn't writing to two different elements of an array, the hard  
part is *ensuring* that you are writing to two different elements of an  
array.  Multithreading code is tough to write correctly, you may want to  
read a book on it.

D2 promises to be a lot better at helping you ensure this.

>
> Also I'm still getting the "Error: Win32 Exception" with my test code  
> any idea
> why? Attached is the latest version.

Just realized from reading your code, you are using D1 with Phobos, I have  
no idea what bugs there are, or how to use threads there, so I can't  
really help you.

I can tell you that your code ported to Tango runs without throwing an  
exception, code below:

import tango.core.Thread;
import tango.io.Stdout;

int count = 0;

void main(){

	Thread testthread;

	void testfunc(){
		while(count<10000000){
			++count;
		}
	}


	testthread = new Thread(&testfunc);
	testthread.start();


	int lastCount = 0;
	while(testthread.isRunning){
		if(count != lastCount){
			Stdout.formatln("{}", count);
			lastCount = count;
		}
	}

}

output:

164
16789
23750
29998
36054
4472263
4482283
4488871
4495320
4501356
4507264
4513158
4518987
4524886
4530722
4536557
4542362
4548221
4554051
4559848
4565753
4571592
4577354
4583152
4588942
4594719
4600579
4606375
4612181
4617981
4623686
4629421


-Steve


More information about the Digitalmars-d-learn mailing list