【问题标题】:Having a Server progress two threads at the same time让服务器同时处理两个线程
【发布时间】:2016-07-20 05:42:59
【问题描述】:

我有两个线程在稍微不同的时间到达服务器程序中的一个点,都发送一个字符串。我希望服务器此时暂停,直到两个线程都收到一个字符串,然后继续。目前我正在使用Console.ReadKey(); 来“暂停”线程。但这不是解决方案,因为我需要按两次键(每个线程一个键)才能继续。

是否有可能在程序类中有一个全局计数器,所有线程随时都可以访问和编辑?与ConcurrentDictionary 类似的概念。这样我就可以根据哪个线程首先发送字符串来区分线程,并使程序挂起,直到计数器对两个客户端都“应答”感到满意。

class Program
{
    public static bool isFirstThread = false;

    static void Main(string[] args)
    {
        runServer();
    }

    static void runServer()
    {
        //server setup
        Thread[] threadsArray = new Thread[2];
        int i = 0;
        try
        {
            while(true) //game loop
            {
                Socket connection;
                connection = listener.AcceptSocket();
                threadRequest = new Handler();

                if(i==0) //first thread
                {
                    threadsArray[i] = new Thread(() => threadRequest.clientInteraction(connection, true);
                }
                else //not first thread
                {
                    threadsArray[i] = new Thread(() => threadRequest.clientInteraction(connection, false);
                }

                threadsArray[i].Start();
                i++;
            }
        }

        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.ToString());
        }
    }
}


class Handler 
{
    public void clientInteraction(Socket connection, bool isFirstThread)

    {
        string pAnswer = string.Empty;
        //setup streamReaders and streamWriters

        while(true) //infinite game loop
        {
            //read in a question and send to both threads.
            pAnswer = sr.ReadLine();
            Console.WriteLine(pAnswer);

            Console.ReadKey(); //This is where I need the program to hang

            awardPoints(); 

        }
    }
}   

这是我的代码在做什么的粗略概念,为了避免问题膨胀,我已经切了很多东西,所以我可能遗漏了一些错误的东西。

理论上我可以从服务器发送问题字符串时开始设置一个计时器,但我宁愿不在这个阶段。

任何想法或指示将不胜感激。提前致谢。

【问题讨论】:

  • 带有条件的while循环?一个变量通常可以由多个线程编辑,除非执行竞争条件。但是,如果您想等待,请使用带有布尔条件的 while 循环。
  • 这个变量应该在哪里声明?我已经尝试在程序类中放置一个,但除非我在创建线程时传递它,否则它不起作用。并且在创建线程时,建议的 while 循环的条件是未知的
  • 您希望两个线程同时继续,还是只继续一个?您始终可以将变量作为 ref 参数传递...

标签: c# multithreading server


【解决方案1】:

使用System.Threading.Barrier,它是专门为这个目的而设计的:让一组线程中的每个线程等待,直到它们都达到计算中的某个点。像这样在runServer() 中初始化它:

Barrier barrier = new Barrier(2);

并在每个线程的末尾执行此操作:

barrier.SignalAndWait();

【讨论】:

  • 不知道这个。不错!
  • 绝对完美。非常感谢。
  • :-) - System.Threading 有很多好东西 - 另一个个人最喜欢的是 AutoResetEvent 让一个线程等待另一个线程向它发送信号。
猜你喜欢
  • 1970-01-01
  • 2022-07-29
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多