Reputation:
I'm using the code below to initialise 4 thread with the same method so that each one can perform the same process but on a separate file.
for (int i = 0; i < 4; i++)
{
Thread newProcessThread = new Thread(ThreadProcessFile)
{
Priority = ThreadPriority.BelowNormal,
IsBackground = true
};
newProcessThread.Start();
}
Inside the ThreadProcessFile method, it starts like this so each thread knows what is its ID is. _threadInitCount
is declared in the same class.
int threadID = _threadInitCount;
_threadInitCount += 1;
However, I'm getting a weird behaviour where a number might be missed or duplicated. e.g. the first thread might have an ID of 1 and not 0 or 2 will be missing from the set of four threads.
Can anyone explain this behaviour or advise on a better way of doing this?
Upvotes: 1
Views: 146
Reputation: 1317
Each thread already has an unique ID assigned to it. You can access it with
Thread.CurrentThread.ManagedThreadId
property.
The reason you get duplicated/missing numbers is that a context switch might occur at every moment. Imagine, for instance, that your threads get executed one-by-one line-by-line. The first thread assigns its threadID variable to _threadInitCount, which is 0. Then the second does the same, its threadID is 0 too. Then the third gets its threadID=0 and so on. Then the first thread turns on again to increase _threadInitCount to 1, then the second increases it to 2 and so on.
Upvotes: 2