Note that there are some explanatory texts on larger screens.

plurals
  1. POwait for another thread
    primarykey
    data
    text
    <p>So I have this program that attempts to establish communication between two different threads, thread1 and thread2.</p> <pre><code>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(() =&gt; thread1())); Thread t2 = new Thread(new ThreadStart(() =&gt; thread2())); t1.Start(); t2.Start(); t2.Join(); t1.Join(); } } } </code></pre> <p>However, I want it to occur such that this line:</p> <pre><code>Console.WriteLine("1"); </code></pre> <p>...gets executed first, while thread2 merely waits for this line to be executed. Then and only then would it print:</p> <pre><code>Console.WriteLine("t1 has printed 1, so we now print 1"); </code></pre> <p>After this line is printed, then and only then would this line:</p> <pre><code>Console.WriteLine("t2 has printed 1, so we now print 2"); </code></pre> <p>...get printed, and so on. So I want to change the code, so that the threads to communicate with each other so that the lines get printed in this order:</p> <pre><code> 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 </code></pre> <p>I understand what lock does, but it only applies if the two different threads are running on the same function. However, here, the two functions are different and thus I can't use lock here.</p> <p>Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload