Sami
Sami

Reputation: 413

mimic concurrent threads (on the same resource/method)

Is there any way that I mimic in an short simple illustrative example of concurrent threads, that 2 threads can start the same method at the same time, and the processing is mixed between the two?

In the below example, I want to see sth like:

1 thread1
1 thread2
2 thread1
2 thread2
..
10 thread1
10 thread2

Instead, I get something like:

1 thread1
2 thread1
...
10 thread1
1 thread2
2 thread2
...
10 thread2

Be kind, I'm just starting to learn threads.

In short, I want to simulate the effect of the two threads starting at exactly the same time, not one immediately after the other.

After I achieve the above mentioned, I want to use the lock in order for thread1 to completely finish executing before starting thread2. This already happens in my example even before employing lock.

using System;
using System.Threading;

    public class Program
    {
        public class C1
        {

            private object obj = new object();


            public void Ten() 
            {
                //lock(obj)
                //{
                    for(int i=1; i<=10; i++)
                    {
                        Console.WriteLine(i + " " + Thread.CurrentThread.Name);
                    }
                //}
            }

        }
        public static void Main()
        {
            Thread t1 = new Thread(new ThreadStart(new C1().Ten));
            Thread t2 = new Thread(new ThreadStart(new C1().Ten));

            t1.Name = "thread1";
            t2.Name = "thread2";

            t1.Start(); 
            t2.Start();
        }
}

Upvotes: 0

Views: 39

Answers (1)

Cinchoo
Cinchoo

Reputation: 6322

as ESG mentioned in the comment, the code runs too fast. That's why you are not getting expected output. Try adding some sleep inside the loop to get the expected result.

using System;
using System.Threading;

    public class Program
    {
        public class C1
        {

            private static object obj = new object();


            public void Ten() 
            {
                //lock(obj)
                //{
                    for(int i=1; i<=10; i++)
                    {
                        Console.WriteLine(i + " " + Thread.CurrentThread.Name);
                        Thread.Sleep(1000); //<-- add sleep
                    }
                //}
            }

        }
        public static void Main()
        {
            Thread t1 = new Thread(new ThreadStart(new C1().Ten));
            Thread t2 = new Thread(new ThreadStart(new C1().Ten));

            t1.Name = "thread1";
            t2.Name = "thread2";

            t1.Start(); 
            t2.Start();
        }
}

On the second note about locking the resource so that thread2 should wait for thread1 to complete. You will need to mark the obj as static variable.

Hope it helps.

Upvotes: 1

Related Questions