creating new threads in a loop

前端 未结 2 1205
太阳男子
太阳男子 2020-12-12 01:30

I\'m trying to understand why this code is not working.

    private static object _lock;

    public static void Main (string[] args)
    {
        Thread th         


        
相关标签:
2条回答
  • 2020-12-12 01:48

    Your lock does not do anything at all; only one thread is locking on that object - the one that is starting the others. Those other threads never contest for that lock at all.

    0 讨论(0)
  • 2020-12-12 01:57

    Because each thread is refering to the loop variable, and does not get its own copy at the time you create the thread.

    Notice that the compiler is warning you: "Access to a modified closure".

        foreach (int num in Enumerable.Range(0,5))
        {
            int loopnum = num;
    
            thread = new Thread(() => print(loopnum.ToString())); 
            thread.Start();  
        }
    
    0 讨论(0)
提交回复
热议问题