黄巾之乱-服务器线程控制

来源:互联网 发布:淘宝衣服调色 编辑:程序博客网 时间:2024/04/24 18:35


我有一个场景:

有N个线程,它们一起执行,等到N个线程执行完成后,有一个A线程执行。

A线程执行完成后,N个线程又一起冲出来,同时执行。  这样周而复始。

(N线程的个数未知,它们的个数可能随时都在变化)


我想要这种结果:

N1线程
N2线程
N3线程
A 线程
------------------
N3线程
N1线程
N2线程
N4线程
A 线程
--------------------
N1线程
N2线程
A 线程
--------------------



之前使用了MS的读写锁来实现,但总觉得不够清晰,自己用代码来实现了:


using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Collections;using System.Threading;using System.Collections.Concurrent;using System.Diagnostics;namespace threadcontrol{     public partial class Form1 : Form    {        static ConcurrentDictionary<int, bool> dict_done = new ConcurrentDictionary<int, bool>();                public Form1()        {            InitializeComponent();            Control.CheckForIllegalCrossThreadCalls = false;                                         Thread aThread = new Thread(new ThreadStart(princess));                        aThread.Start();                    }        private void button1_Click(object sender, EventArgs e)        {                      Thread nThread = new Thread(new ThreadStart(dwarf));            nThread.Start();        }        private void dwarf()        {            int hashid = Thread.CurrentThread.ManagedThreadId;            dict_done.TryAdd(hashid, false);            while (true)            {                if (dict_done[hashid]) { Thread.Sleep(100); }                else {                                            //do something                        listBox1.Items.Insert(0, "dwarf");                        dict_done[hashid] = true;                      }            }        }        private void princess()        {            while (true)            {                if (!all_done()) { Thread.Sleep(100); } //有人没完成                else { //全部完成                                        Thread.Sleep(1000);                    listBox1.Items.Insert(0, "--------------princess  " + dict_done.Count.ToString());                    set_kong();//全部读线程初始                    }            }        }        public bool all_done()        {           bool tmp = true;           foreach (var key in dict_done.Keys)                {                    if (dict_done[key] == false) { tmp = false; break; }                }            return tmp;        }        public void set_kong()                {                     foreach (var key in dict_done.Keys)            {                dict_done[key] = false;            }                  }      }}





0 0