zenith
zenith

Reputation: 61

how to lock global variable in multi thread?

I have two thread ,Each running two threads, no error appear. but run together,the backgroundWorker2 tip :can't clone null.....(I check variable J value is greater than 100),in this case,how to lock global variable?

Bitmap img; //global variable
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int i = 0;
        do
        {
            img = (Bitmap)Image.FromFile(@"i:\1.jpg");
            img.Dispose();
            i++;
            backgroundWorker3.ReportProgress(i,"");
            Thread.Sleep(10);
        } while (!backgroundWorker4.CancellationPending);
    }

 private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
        int j= 0;
        do
        {
            //img = (Bitmap)Image.FromFile(@"i:\1.jpg");

            if (img != null)
            {
                lock (img)
                {
                    Bitmap tempImg = (Bitmap)img.Clone();
                }
            }

            j++;
            backgroundWorker4.ReportProgress(j, "");
            Thread.Sleep(10);
        } while (!backgroundWorker4.CancellationPending);
    }

Upvotes: 0

Views: 2484

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

It looks like you need a double-checked lock. This prevents the scenario where, in between the null check and the locking, another thread sets img to null (ie, a race condition).

if (img != null)
{
    lock (img)
    {
        if (img != null)
        {
            Bitmap tempImg = (Bitmap)img.Clone();
        }
    }
}

Upvotes: 1

Related Questions