Autoresetevent and ++i

34 Views Asked by At

This code snippet is very clear and the question is also very simple: why the cnt is not equals to 0?

This code shows:

  • t1 is producer, add i,
  • t2 is consumer, eat i, set an int array.

In my thought, when t1 add i, it waits t2 to consume it. After t2 set the array, then, notify t1 to continue to run.

I know t2 may run twice or even more per i. But I think it doesn't matter. Please tell me what is wrong.

The result looks like:

min: 22, count: 1059, 0.00100994206423003

data[311106]: 0
data[311111]: 0
data[311516]: 0
data[312153]: 0
data[312801]: 0
data[312873]: 312874
data[313223]: 0
data[313276]: 0
data[313400]: 0
data[315358]: 0
data[317888]: 0

    AutoResetEvent m1 = new AutoResetEvent(false);
    int i = 0;
    int[] data = new int[0x100000];
    Task t1 = Task.Run(() =>
    {
        Console.WriteLine("t1 run");
        while (i < 0x0fffff)
        {
            m1.WaitOne();
            ++i;
        }
        Console.WriteLine("t1 done");
    
    });
    
    Task t2 = Task.Run(() =>
    {
        Console.WriteLine("t2 run");
        while (i < 0x0fffff)
        {
            data[i] = i;
            m1.Set();
        }
        Console.WriteLine("t2 done");
    
    });
    
    Task.WaitAll(t1, t2);
    
    int cnt = 0;
    int min = 0x0fffff;
    for (int j = 0; j < 0x0fffff; ++j)
    {
        if (data[j] != j)
        {
            min = Math.Min(min, j);
            cnt++;
            Console.WriteLine($"data[{j}]: {data[j]}");
        }
    }
    
    Console.WriteLine($"min: {min}, count: {cnt}, {cnt * 1.0 / 0x0fffff}");

Why the cnt is not equals to 0?

0

There are 0 best solutions below