Right Now, it outputs 00, instead of 54. I’m learning with threads and I stuck here, I don’t know what to do now
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Point[] array = new Point[20];
public Form1()
{
for (int i = 0; i < 20; i++)
{
array[i] = new Point(); // I'm creating objects here
}
InitializeComponent();
}
void function1()
{
array[0].x = 5;
array[0].y = 4;
}
void function2()
{
label1.Text = array[0].ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread1 = new Thread(function1);
thread1.Start();
Thread.Sleep(500);
function2();
}
}
class Point
{
public int x;
public int y;
public override string ToString()
{
return x.ToString() + y.ToString();
}
}
}
when Im doing it in that way (without another thread)
private void Form1_Load(object sender, EventArgs e)
{
function1();
function2();
}
It works fine, output is 54
thanks
Actually your program is working on my computer as expected. So why it’s not working on your computer (or is working only sometimes)? This is because there is race condition in your program. This means that your program assumes that the second thread (that executes function1) will assign new values to array in less than 500ms. Never make any ASSUMPTION about how long it takes for the other thread to complete it’s task. Operating system is free to choose when, how often and how long individual threads executes and when it suspends them. Instead, use synchronization primitives (such as ManualResetEvent) to MAKE SURE that the second thread has done it’s task.
This code shows, how you can change your program do thread synchronization properly: