Threading
Saaa
empty at needmail.com
Tue May 12 08:42:27 PDT 2009
>>>
>>>> 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.
I used to think of an array as one thing, thus making it unsafe to write to
it
from multiple threads at the same time :)
I kind of thought he was asking along this conception.
>
>>
>>>
>>> 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
Could become more difficult if the distinction would be odd/even elements :P
Or creatures on a grid who can only see the cell they stand on :D
But yes, slicing is neat!
More information about the Digitalmars-d-learn
mailing list