I need to assign continuous Ids for some threads when i'm creating them, and doesn't matter what starting id is (like 11, 12 , 13,.. or 9, 10, 11)
This is what i have done, here i am creating 4 threads and invoke My_function()
for ( byte i = 0 ; i < 4 ; i++ )
{
myThreadArray[i] = new Thread(new ParameterizedThreadStart(My_function));
myThreadArray[i].Start(i);
}
it seems working but can i be guaranteed that i always assign continuous id's for them
Thread IDs can be recycled. Your code is starting a thread and waiting for it to finish. There are never more then one (apart from the main-thread) running. Hence, you get the same ID.
In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.
You can create the array of threads (or list of threads, even) anywhere outside the for loop. Yes, collect them in an array. Or use an ExecutorService and awaitTermination().
In some threads implementations, the thread ID is a 4-byte integer that starts at 1 and increases by 1 every time a thread is created. This integer can be used in a non-portable fashion by an application.
Since you are using an array to contain your threads, each sequentially assigned element of that array will have a sequential index.
However, if you need to map a Thread ID to an element in MyThreadArray
, since you have no control over thread ID
s when the threads are created (only the thread Name
), you could use a Dictionary<int, int>
to map the actual thread ID
s to the MyThreadArray
index
for ( byte i = 0 ; i < 4 ; i++ )
{
myThreadArray[i] = new Thread(new ParameterizedThreadStart(My_function));
myThreadArray[i].Start(i);
MyThreadDictionary.Add(MyThreadArray[i].ManagedThreadId(), i)
}
and access it by:
logSet[MyThreadDictionary(System.Threading.Thread.CurrentThread.ManagedThreadId)]
or use Array.FindIndex
to retrieve the index of the MyThreadArray
element that contains the thread matching the thread ID you want to match, in much the same way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With