Threading

Steven Schveighoffer schveiguy at yahoo.com
Tue May 12 07:27:43 PDT 2009


On Tue, 12 May 2009 10:12:48 -0400, Saaa <empty at needmail.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.
> That is why the question was whether it was safe.

If two threads are writing to two different sections of memory, yes it is  
always safe :)  I think that's one of the fundamental premises of threads  
running anyways.  If you couldn't do this, you couldn't have threads.

>
>>
>> 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.
> And sometimes it is extremely easy to ensure you are never writing to the
> same elements.

If you are doing anything interesting with an array, this is not the  
case.  Might as well not pass the same array to both threads.

Maybe the OP doesn't understand that you can slice up an array quite  
easily.  If you want to ensure two threads don't touch the same memory,  
don't give both threads access to the same memory.  That's the easiest way  
to ensure thread safety.

i.e. I want thread 1 to initialize elements 0, 1, and 2, and thread 2 to  
initialize elements 3, 4, and 5:

thread1 = new ProcessingThread(arrayToInit[0..3]);
thread2 = new ProcessingThread(arrayToInit[3..6]);
thread1.start();
thread2.start();

Should be completely thread safe.

-Steve


More information about the Digitalmars-d-learn mailing list