J
Jarod
Hi!
I've done some code using threading just to check if writing code improperly
can cause serious issues when using somehow safe data types.
So in my understanding a stack ( collection type ) won't give any item more
than once. But it does !!!
Again I wrote this code improperly to see what happens but I don't
understand why it happens so if you understand the issue only than reply
private void btnTestThreading_Click(object sender, EventArgs e)
{
Stack<int> numbersStack = new Stack<int>();
for (int i = 0; i < 100; i++)
numbersStack.Push(i);
for (int i = 0; i < 10; i++)
{
Thread th = new Thread(delegate()
{
// i'm putting this as a reference so it should be
shared nicely
TestThreading(ref numbersStack, i);
}
);
th.Start();
}
}
private void TestThreading(ref Stack<int> numbers, int threadNumber)
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(numbers.Peek() * 10);
Console.WriteLine("Thread with number " + threadNumber +
"\t\t processed item " + numbers.Pop());
}
}
In my understanding the worst case scenario here would be 2 threads
accessing stack in the same time ( i'm not using any locks ) and than the
same item would be 'processed' twice. But what happens is 1 thread is getting
the same item twice...
HOW it's possible ? I would understand if it was other thread but it's the
same one. If you delete Thread.Sleep it stops ( at least at mine
Thanks
Jedrzej
I've done some code using threading just to check if writing code improperly
can cause serious issues when using somehow safe data types.
So in my understanding a stack ( collection type ) won't give any item more
than once. But it does !!!
Again I wrote this code improperly to see what happens but I don't
understand why it happens so if you understand the issue only than reply
private void btnTestThreading_Click(object sender, EventArgs e)
{
Stack<int> numbersStack = new Stack<int>();
for (int i = 0; i < 100; i++)
numbersStack.Push(i);
for (int i = 0; i < 10; i++)
{
Thread th = new Thread(delegate()
{
// i'm putting this as a reference so it should be
shared nicely
TestThreading(ref numbersStack, i);
}
);
th.Start();
}
}
private void TestThreading(ref Stack<int> numbers, int threadNumber)
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(numbers.Peek() * 10);
Console.WriteLine("Thread with number " + threadNumber +
"\t\t processed item " + numbers.Pop());
}
}
In my understanding the worst case scenario here would be 2 threads
accessing stack in the same time ( i'm not using any locks ) and than the
same item would be 'processed' twice. But what happens is 1 thread is getting
the same item twice...
HOW it's possible ? I would understand if it was other thread but it's the
same one. If you delete Thread.Sleep it stops ( at least at mine
Thanks
Jedrzej