Hello
I currently have a program which can run 1-10 threads. all of the threads
are exactly the same. These threads access internet pages and therefore
run at different speeds. I now need to know which thread hits a certain
command in the thread 1st, which one is 2nd, which one is 3rd and so on.
can anyone suggest how I could do this please.
Thanks
Jon
Many different approaches you can take, but I think indexing an array with
a shared variable would be easiest. For example, in the class that
implements the code you execute in your threads:
static int[] _threadRegister = new int[10];
static int _registerIndex = -1;
void RegisterCheckpoint()
{
int localIndex = System.Threading.Interlocked.Increment(ref
_registerIndex);
_threadRegister[localIndex] =
System.Threading.Thread.CurrentThread.ManagedThreadId;
}
Each thread would call the RegisterCheckpoint() method after it hits your
certain command. By using the Interlocked() class, each thread would get a
unique index into the array, into which it copies its ID number.
Note that the above is somewhat more efficient at the expense of precision.
There's a race condition in which a thread could hit the checkpoint of
interest itself first, but then get pre-empted, allowing some other thread
to register its arrival at the checkpoint earlier.
Typically, this should not be a problem...if your threads are so close in
execution that this would occur, it's debatable whether it really matters
which winds up registering itself first. But if you really really care
about it, you can use a full lock around the checkpoint to ensure that
the thread that arrives at the start of the checkpoint first is always the
one that registers itself. For example:
static readonly object _lock = new object();
void ActualWorkingMethod()
{
// do some stuff here
// other stuff here
// here's our checkpoint:
lock (_lock)
{
_threadRegister[++_registerIndex] =
Thread.CurrentThread.ManagedThreadId;
// do checkpoint work here
}
}
The above will ensure that the same thread that gets to do the "checkpoint
work" first is always exactly the thread that is also registered first.
The above is just sample code. You may want to adjust it so that the
registration array is allocated according to the actual number of threads,
store it in a different place, use something other than the ManagedThreadId
as the thread identifier in your registration array, etc.