Link to home
Start Free TrialLog in
Avatar of WingYip
WingYip

asked on

Threads and arrays

Hi, any threading gurus out there?

I have an application that starts 6 different threads.  Each thread will create an httpwebrequest and post off to its destination and then wait for a response.

When the response returns each thread will then insert its response into an array that has been declared globally in the application.

Each thread will know its index position number in the array and so will automatically know where its response should go.

My question is this.  The part of my code which inserts into the global array could feasibly be accessed by more than one thread at a time will this cause a problem?  The answer is not obvious to me.  I would have thought that all should be OK as the index number is known and there is no danger of inserting responses in the wrong order.

However, thought I should check

Wing
ASKER CERTIFIED SOLUTION
Avatar of neilmjohnson
neilmjohnson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Alkali_Guy
Alkali_Guy

It is never inherently dangerous to have the same _code_ executed by multiple threads.  That's just bread-and-butter threading.  It is also safe for threads to modify separate indices in a statically allocated array concurrently.
Array and index is OK in the case if you don't need to remove elements. If you need to remove them, I suggest you to use ArrayList or List<T>, and keep reference to added data instead of index. Container (array, list etc.) must be protected using Monitor or lock keyword, for example:

lock(this)
{
    // access data kept in container
}
Additional information:
You need locking when elements are added to container and removed from it. Accessing element itself doesn't require locking, as mentioned in Alkali_Guy's post.
Avatar of WingYip

ASKER

Just needed the confirmation.  Thanks for all the help

Wing