Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make threads with continuous id's

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

like image 385
mhs Avatar asked Sep 09 '13 00:09

mhs


People also ask

Can threads have the same ID?

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.

Can you make multiple thread to execute same instructions?

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.

Can you make an array of threads?

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().

Does a thread have an ID?

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.


1 Answers

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 IDs when the threads are created (only the thread Name), you could use a Dictionary<int, int> to map the actual thread IDs 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.

like image 77
Monty Wild Avatar answered Oct 07 '22 07:10

Monty Wild