Синхронизация двух потоков с AutoResetEvent

Я пытаюсь реализовать AutoResetEvent. Для этой цели я использую очень простой класс:

public class MyThreadTest
{
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
    static readonly AutoResetEvent thread2Step = new AutoResetEvent(false);

    void DisplayThread1()
    {
        while (true)
        {
            Console.WriteLine("Display Thread 1");

            Thread.Sleep(1000);
            thread1Step.Set();
            thread2Step.WaitOne();
        }
    }

    void DisplayThread2()
    {
        while (true)
        {
            Console.WriteLine("Display Thread 2");
            Thread.Sleep(1000);
            thread2Step.Set();
            thread1Step.WaitOne();
        }
    }

    void CreateThreads()
    {
        // construct two threads for our demonstration;
        Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
        Thread thread2 = new Thread(new ThreadStart(DisplayThread2));

        // start them
        thread1.Start();
        thread2.Start();
    }

    public static void Main()
    {
        MyThreadTest StartMultiThreads = new MyThreadTest();
        StartMultiThreads.CreateThreads();
    }
}

Но это не работает. Использование кажется очень простым, поэтому я был бы признателен, если бы кто-нибудь смог показать мне, что не так и где проблема с логикой, которую я здесь реализую.


person Leron_says_get_back_Monica    schedule 23.01.2013    source источник
comment
Как это не работает? Что происходит?   -  person SLaks    schedule 23.01.2013
comment
Ну, код, который вы дали, даже не скомпилируется - вы никогда не объявляли _stopThreads...   -  person Jon Skeet    schedule 23.01.2013
comment
@ Jon Skeet Я просто изменил код, чтобы изолировать проблему, теперь она исправлена.   -  person Leron_says_get_back_Monica    schedule 23.01.2013
comment
@Slaks Я хочу получить синхронизированный вызов, но это не так.   -  person Leron_says_get_back_Monica    schedule 23.01.2013
comment
Чего вы ожидаете?   -  person Anton Tykhyy    schedule 23.01.2013
comment
@Leron Это работает на моем ПК. Какую синхронизацию вы хотите добиться между потоками?   -  person Adrian Ciura    schedule 23.01.2013
comment
Ваш код, похоже, гарантирует, что оба потока пишут консольное сообщение примерно в одно и то же время. Что вы хотите, чтобы он делал?   -  person C.Evenhuis    schedule 23.01.2013
comment
@Adrian Ciura Я хочу видеть Display Thread 1, Display Thread 2, Display Thread 1, отображать поток 2 и т. д., не меняя порядок, например Display Thread 1, Display Thread 1 или Display Thread 2, Display Thread 2.   -  person Leron_says_get_back_Monica    schedule 23.01.2013
comment
Другими словами, я хочу установить порядок выполнения 1-2-1-2-1-2 и так далее, а не как сейчас 1-2-1-2-2-1-1-2...   -  person Leron_says_get_back_Monica    schedule 23.01.2013


Ответы (1)


Вопрос не очень ясен, но я предполагаю, что вы ожидаете, что он отобразит 1,2,1,2...

Тогда попробуйте это:

public class MyThreadTest
{
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
    static readonly AutoResetEvent thread2Step = new AutoResetEvent(true);

    void DisplayThread1()
    {
        while (true)
        {
            thread2Step.WaitOne(); 
            Console.WriteLine("Display Thread 1");
            Thread.Sleep(1000);
            thread1Step.Set();
        }
    }

    void DisplayThread2()
    {
        while (true)
        {
            thread1Step.WaitOne(); 
            Console.WriteLine("Display Thread 2");
            Thread.Sleep(1000);
            thread2Step.Set();
        }
    }

    void CreateThreads()
    {
        // construct two threads for our demonstration;
        Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
        Thread thread2 = new Thread(new ThreadStart(DisplayThread2));

        // start them
        thread1.Start();
        thread2.Start();
    }

    public static void Main()
    {
        MyThreadTest StartMultiThreads = new MyThreadTest();
        StartMultiThreads.CreateThreads();
    }
}
person Eren Ersönmez    schedule 23.01.2013