So, I have this program that is trying to establish a connection between two different threads, thread1 and thread2.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Project1 { class Class1 { public static void thread1() { Console.WriteLine("1"); Console.WriteLine("t2 has printed 1, so we now print 2"); Console.WriteLine("t2 has printed 2, so we now print 3"); } public static void thread2() { Console.WriteLine("t1 has printed 1, so we now print 1"); Console.WriteLine("t1 has printed 2, so we now print 2"); Console.WriteLine("t1 has printed 3, so we now print 3"); } public static void Main() { Thread t1 = new Thread(new ThreadStart(() => thread1())); Thread t2 = new Thread(new ThreadStart(() => thread2())); t1.Start(); t2.Start(); t2.Join(); t1.Join(); } } }
However, I want this to happen so that this line:
Console.WriteLine("1");
... is executed first, and thread2 just waits for this line to execute. Then and only then will it print:
Console.WriteLine("t1 has printed 1, so we now print 1");
After this line is printed, then and only then this line:
Console.WriteLine("t2 has printed 1, so we now print 2");
... to be printed, etc. Therefore, I want to change the code so that the threads communicate with each other, so that the lines are printed in the following order:
Console.WriteLine("1"); // from t1 Console.WriteLine("t1 has printed 1, so we now print 1"); // from t2 Console.WriteLine("t2 has printed 1, so we now print 2"); // from t1 Console.WriteLine("t1 has printed 2, so we now print 2"); // from t2 Console.WriteLine("t2 has printed 2, so we now print 3"); // from t1 Console.WriteLine("t1 has printed 3, so we now print 3"); // from t2
I understand what the lock does, but only applies if two different threads are running on the same function. However, the two functions are different here, and therefore I cannot use the lock here.
Any ideas?