Esempio n. 1
0
 //выбирает ход для выбранного игрока с глубиной не более maxDeep
 public Step SelectMove(Player p, int maxDeep, Board board)
 {
     Count = 0;
     _maxDeep = maxDeep;
     _threadsResults.Clear();
     var nBoard = new Board(board);
     var game = new Game(nBoard);
     var moves = game.getAllLegalMoves(p);
     var b = moves.Batch(moves.Count/ThreadCount).ToList();
     var thraads = new Thread[b.Count];
     var n = 0;
     foreach (var curMoves in b)
     {
         var args = new TheadArg
         {
             board = new Board(board),
             startPlayer = p,
             steps = curMoves.ToList()
         };
         var thread = new Thread(Process) {IsBackground = true};
         thread.Start(args);
         thraads[n++] = thread;
     }
     while (thraads.Any(x => x.IsAlive))
     {
         Thread.Sleep(100);
     }
     var res = _threadsResults.MaxBy(x => x.Score);
     return res.Step;
 }
Esempio n. 2
0
        /// <summary>
        /// Main class action
        /// </summary>
        private void DoBruteForce()
        {
            int bitCapacityNeeded;
            long rangeFloor, rangeCeiling;
            lock (_field)
            {
                _field.ViewField();
                Console.WriteLine("Building routes...");
                _successfulMovements = new Dictionary<int, string>();
                bitCapacityNeeded = (_field.Height - 1) + (_field.Width - 1);
                rangeFloor =
                    Convert.ToInt64(
                        new StringBuilder().Append('0', (_field.Height + _field.Width - 2) / 2)
                            .Append('1', (_field.Height + _field.Width - 2) / 2).ToString(), 2);
                rangeCeiling = Convert.ToInt64(
                    new StringBuilder().Append('1', (_field.Height + _field.Width - 2) / 2)
                        .Append('0', (_field.Height + _field.Width - 2) / 2).ToString(), 2);
            }

            Thread[] threads = new Thread[_threadsCount];
            Parameter[] parameters = new Parameter[_threadsCount];
            for (int i = 0; i < _threadsCount; i++)
            {
                threads[i] = new Thread(PerformUniqueTask);
                parameters[i] = new Parameter(_threadsCount, i, rangeFloor, rangeCeiling, bitCapacityNeeded);
                threads[i].Start(parameters[i]);
            }
            while (threads.Any(t => t.IsAlive))
                Thread.Yield();
            Console.WriteLine("All routes built.");
        }
Esempio n. 3
0
        /// <summary>
        /// Adds a 4 dimensional dataSet to the DateMatrix by disceminating the data from the given DataSet
        /// </summary>
        /// <param name="key">The key they dataSet should be stored under</param>
        /// <param name="dataSet">The System.DataSet to disceminate</param>
        /// <param name="dateTimeField">The field in the DataSet which is of type DateTime</param>
        /// <param name="dataField">The field in the DataSet which is to be used in the 4 dimensional dataSet for values</param>
        public void AddDataSet(string key, DataSet dataSet, string dateTimeField, string dataField)
        {
            //make a place to hold the data we are sharing amount threads
            T[, , ,] newData = new T[31, 24, 60, 60];
            //determine the record count
            int count = dataSet.Tables[0].Rows.Count - 1; //T
            //set the amount of records each thread will process
            int threadRecords = 5000;                     //Mx
            //detmine the amount of threads it will take
            int threadCount = count / threadRecords;      //Tx

            //add one for the difference in the last thread
            threadCount++;

            //allocate threads
            Thread[] threads = new Thread[threadCount];

            //start at 0
            int start = 0;

            int lastThread = threadCount - 1;

            for (int threadIndex = 0; threadIndex < threadCount; threadIndex++)
            {
                //If this is the thread which takes care of the difference then use count - name which is start
                if (threadIndex == lastThread)
                {
                    threads[threadIndex]          = new Thread(new ParameterizedThreadStart(AddDataSetThreaded));
                    threads[threadIndex].Priority = ThreadPriority.AboveNormal;
                    threads[threadIndex].SetApartmentState(ApartmentState.MTA);
                    threads[threadIndex].Start(new AddThreaded(start, Math.Abs((count - start)), ref dataSet, ref dateTimeField, ref dataField, ref newData));
                }
                else
                {
                    //If this is a thread which does not take care of diffrence then use name which is start
                    threads[threadIndex]          = new Thread(new ParameterizedThreadStart(AddDataSetThreaded));
                    threads[threadIndex].Priority = ThreadPriority.AboveNormal;
                    threads[threadIndex].SetApartmentState(ApartmentState.MTA);
                    threads[threadIndex].Start(new AddThreaded(start, threadRecords, ref dataSet, ref dateTimeField, ref dataField, ref newData));
                }
                start += threadRecords;
            }

            ///move execution time away from this thread
            Thread.CurrentThread.Priority = ThreadPriority.Lowest;

            //while any thread is working
            while (threads.Any(thread => thread.IsAlive == true))
            {
                //sleep indefinitely for it to complete
                Thread.Sleep(0);
            }

            Thread.CurrentThread.Priority = ThreadPriority.Normal;

            //add the dataset to the dataDictionary.
            AddDataSet(key, newData);
        }
Esempio n. 4
0
        /// <summary>
        ///     被动监测目前局域网内的所有设备(导致阻塞)。
        /// </summary>
        /// <exception cref="TimeoutException">等待分析线程终止超时。</exception>
        public void SpyForTarget()
        {
            // 获取当前设备
            var device = DeviceList[CurDevName];

            // 创建分析线程
            var analyzeThreads = new Thread[8];

            try {
                // 开始扫描
                device = StartCapture("arp");

                // 初始化分析线程
                for (var i = 0; i < 8; i++)
                {
                    analyzeThreads[i] = new Thread(ScanPacketAnalyzeThread);
                    analyzeThreads[i].Start();
                }

                // 如果分析线程异常终止,则结束监听
                while (analyzeThreads.All(analyzeThread => analyzeThread.IsAlive))
                {
                    Thread.Sleep(800);
                }
            }
            catch (ThreadAbortException) {
                // 终止分析线程
                foreach (var analyzeThread in analyzeThreads)
                {
                    analyzeThread.Abort();
                }
            }
            finally {
                // 终止分析线程
                foreach (var analyzeThread in analyzeThreads)
                {
                    if (analyzeThread.IsAlive)
                    {
                        analyzeThread.Abort();
                    }
                }

                // 等待分析线程终止
                new WaitTimeoutChecker(30000).ThreadSleep(500, () => analyzeThreads.Any(analyzeThread => analyzeThread.IsAlive));

                // 清理缓冲区及其他内容
                lock (_hostList) {
                    _hostList.Sort(Host.SortMethod);
                }
                StopCapture(device);
                ClearCaptures();
            }
        }
Esempio n. 5
0
        public void UpdateUserInfo()
        {
            DateTime start = DateTime.Now;
            DateTime end   = DateTime.Now;

            try
            {
                UserInfoService userInfoService = new UserInfoService();
                List <string>   list            = userInfoService.Select().Select(x => x.openid).ToList();
                //List<string> list = db.UserInfo.Select(x => x.openid).ToList();
                Thread[] thread = new Thread[20];
                for (int i = 0; i < thread.Length; i++)
                {
                    thread[i] = new Thread(() =>
                    {
                        while (list.Count > 0)
                        {
                            string openid = "";
                            lock (userInfoService)
                            {
                                if (list.Count > 0)
                                {
                                    openid = list[0];
                                    list.Remove(openid);
                                    userInfoService.UpdateByOpenid(openid);
                                }
                            }
                        }
                    })
                    {
                        IsBackground = true
                    };
                    thread[i].Start();
                }
                while (thread.Any(x => x.ThreadState != ThreadState.Stopped))
                {
                    Thread.Sleep(500);
                }
                end = DateTime.Now;
                Response.Write("更新成功,耗时:" + (end - start).TotalSeconds + "秒!");
            }
            catch (Exception ex)
            {
                end = DateTime.Now;
                Response.Write("更新失败,耗时:" + (end - start).TotalSeconds + "秒!");
            }
        }
Esempio n. 6
0
        private int FindInput(Func <byte[], bool> isMatch)
        {
            Thread[] threads = new Thread[ThreadCount];

            for (int i = 0; i < ThreadCount; i++)
            {
                int start = i + 1;
                threads[i] = new Thread(() => FindInputThread(isMatch, start));
                threads[i].Start();
            }

            while (threads.Any(t => t.IsAlive))
            {
            }

            return(_targetInput);
        }
        public int Run()
        {
            var threads     = new Thread[_noOfThreads];
            var threadDatas = new ThreadRunner[_noOfThreads];

            for (var i = 0; i < _noOfThreads; i++)
            {
                var threadRunner = new ThreadRunner(DefaultTestingThreadReportingPeriod, _loggerFactory.CreateLogger <ThreadRunner>());
                threads[i]     = new Thread(threadRunner.RunLoop);
                threadDatas[i] = threadRunner;
                threads[i].Start();
            }

            var monitoringThread     = new Thread(MonitoringThread);
            var monitoringThreadData = new MonitoringThreadData(threadDatas);

            monitoringThread.Start(monitoringThreadData);

            Thread.Sleep(_timeToRun);
            _logger.LogInformation("Exiting worker threads");
            foreach (var threadData in threadDatas)
            {
                threadData.ShouldStop = true;
            }

            _logger.LogInformation("Exiting monitoring thread");
            monitoringThreadData.WaitHandle.Set();
            monitoringThread.Join();

            Thread.Sleep(DefaultTestingThreadReportingPeriod.Multiply(2));

            foreach (var thread in threads)
            {
                if (thread.IsAlive)
                {
                    _logger.LogWarning($"Worker thread {thread.ManagedThreadId} still alive");
                }
            }

            var aliveThreads = threads.Any(x => x.IsAlive);
            var failRun      = ReportRunResult(threadDatas);

            return(failRun || aliveThreads ? 1 : 0);
        }
        public void Start()
        {
            if (!Directory.GetParent(TreePath).Exists)
            {
                Directory.CreateDirectory(Directory.GetParent(TreePath).ToString());
            }

            if (File.Exists(TreePath))
            {
                File.Delete(TreePath);
            }

            FileReaderLogic root = new FileReaderLogic(ViewPath, TreePath, LogPath);

            Thread[] ThreadArray = new Thread[3];
            //     Parallel.Invoke(()=> { root.Start(); }, () => { root.Start(); }, () => { root.Start(); });
            for (var i = 0; i < ThreadArray.Length; i++)
            {
                ThreadArray[i] = new Thread(root.Start);
                ThreadArray[i].Start();
                ThreadArray[i].Name = (i + 1).ToString();
            }

            bool stop = false;

            while (true)
            {
                if (stop)
                {
                    break;
                }
                _key = Console.ReadKey(true);

                if (!ThreadArray[0].IsAlive && !ThreadArray[0].IsAlive && !ThreadArray[0].IsAlive) //if(!ThreadArray.All(x => x.IsAlive))
                {
                    Console.WriteLine("All thread are stopped");
                }

                switch (_key.Key)
                {
                case ConsoleKey.Spacebar:
                {
                    if (ThreadArray.Any(x => x.ThreadState == ThreadState.Running))
                    {
                        root.WaitHandler.Reset();
                    }
                    else
                    {
                        root.WaitHandler.Set();
                    }
                    break;
                }

                case ConsoleKey.F1:
                {
                    foreach (Thread thr in ThreadArray)
                    {
                        Console.WriteLine(thr.Name + " " + thr.ThreadState + " " + thr.IsAlive);
                    }
                    break;
                }

                case ConsoleKey.Escape:
                {
                    foreach (Thread thr in ThreadArray)
                    {
                        thr.Abort();
                    }
                    stop = true;
                    break;
                }
                }
            }

            Console.WriteLine("--------------------------");
            File.WriteAllLines(TreePath, root.FolderList);
            File.AppendAllLines(TreePath, root.FileList);

            Console.WriteLine("Done");
        }
Esempio n. 9
0
        //private void MatchBodies()
        //{
        //	Console.WriteLine("Load Bodies");
        //	SystemBody[] bodies;
        //	using (var systemFs = new FileStream(@"C:\Users\Jean-\Desktop\bodies7days.json", FileMode.Open))
        //	{
        //		using (var systemStreamReader = new StreamReader(systemFs))
        //		{
        //			using (var jsonReader = new JsonTextReader(systemStreamReader))
        //			{
        //				var jsonSerializer = new JsonSerializer();
        //				bodies = jsonSerializer.Deserialize<SystemBody[]>(jsonReader);
        //			}
        //		}
        //	}

        //	Console.WriteLine("Match Bodies");
        //	var count = 0;
        //	Parallel.For(0, Systems.Length, (i, state) =>
        //	{
        //		var system = Systems[i];
        //		system.SystemBodies = bodies.Where(e => e.SystemId64 == system.Id64).ToArray();
        //		var e = Interlocked.Add(ref count, 1);
        //		if (e % 50 == 0)
        //		{
        //			Console.WriteLine($"{count} - {Systems.Length}");
        //		}
        //	});
        //	Console.WriteLine();

        //	var usefullSystems = SystemsOfInterest
        //		.Where(e => e.SystemBodies?.Any() == true)
        //		.Where(e => e.SystemBodies.Any(f => f.Rings?.Any(g => g.Type == "Icy") == true))
        //		.ToArray();

        //	var serializeObject = JsonConvert.SerializeObject(usefullSystems);
        //	File.WriteAllText("usefullSystems.json", serializeObject);
        //}

        private async Task LoadAndFilterSystems()
        {
            Console.WriteLine("Load Systems");
            var foundSystems      = 0L;
            var skippedSystems    = 0L;
            var seralizationQueue = new BlockingCollection <string>();
            var resultSet         = new ConcurrentBag <SystemModel>();
            var threads           = new Thread[Environment.ProcessorCount - 4];

            var processPerSecound = 0;
            var readingPerSecound = 0;

            for (int i = 0; i < threads.Length; i++)
            {
                var thread = new Thread(() =>
                {
                    foreach (var toSerialize in seralizationQueue.GetConsumingEnumerable())
                    {
                        try
                        {
                            var deserializeObject = JsonConvert.DeserializeObject <SystemModel>(toSerialize);
                            if (deserializeObject.InRangeOf(SolReference.Coordinates, SearchDistance))
                            {
                                resultSet.Add(deserializeObject);
                                Interlocked.Add(ref foundSystems, 1);
                            }
                            else
                            {
                                Interlocked.Add(ref skippedSystems, 1);
                            }
                        }
                        catch (Exception e)
                        {
                            Interlocked.Add(ref skippedSystems, 1);
                            continue;
                        }
                        Interlocked.Add(ref processPerSecound, 1);
                    }
                });
                thread.Name = "Eval" + i;
                threads[i]  = thread;
                thread.Start();
            }


            var bytes = 0L;
            var size  = 0L;
            var task  = Task.Run(async() =>
            {
                var runningSince = DateTime.Now;
                while (!seralizationQueue.IsAddingCompleted || threads.Any(f => f.IsAlive))
                {
                    await Task.Delay(1000);
                    Console.CursorLeft = 0;
                    var progress       = Math.Round((((bytes / (decimal)size)) * 100), 2);
                    Console.Write($"Progress: {progress}, " +
                                  $"found: {foundSystems}, " +
                                  $"skipped: {skippedSystems}, " +
                                  $"time: {(DateTime.Now - runningSince):g}, " +
                                  $"Queued: {seralizationQueue.Count}," +
                                  $"Reading/s: {readingPerSecound} " +
                                  $"Writing/s: {processPerSecound} ");
                    readingPerSecound = 0;
                    processPerSecound = 0;
                }
            });

            await Task.Run(() =>
            {
                long counter = 0;
                using (var systemFs = new FileStream(@"H:\galaxy.json\galaxy.json",
                                                     FileMode.Open, FileAccess.Read, FileShare.None, 2024, FileOptions.SequentialScan))
                {
                    size = systemFs.Length;
                    using (var streamReader = new StreamReader(systemFs, Encoding.UTF8, true))
                    {
                        while (!streamReader.EndOfStream)
                        {
                            if (seralizationQueue.Count > 1000000)
                            {
                                Thread.Sleep(TimeSpan.FromSeconds(15));
                            }

                            counter++;
                            var line = streamReader.ReadLine().Trim(' ', ',', '\t', '\n', '\r');
                            if (line.StartsWith('{') && line.EndsWith('}'))
                            {
                                seralizationQueue.Add(line);
                            }

                            readingPerSecound++;
                            bytes = systemFs.Position;
                        }
                    }
                }
            });

            seralizationQueue.CompleteAdding();
            Console.WriteLine("Adding complete");
            foreach (var thread in threads)
            {
                thread.Join();
            }

            await task;

            Console.WriteLine("Serialize Objects");
            var serializeObject = JsonConvert.SerializeObject(resultSet.ToArray());

            File.WriteAllText("usefulSystems.json", serializeObject);

            Console.WriteLine("Done");
            Console.ReadLine();

            //SystemsOfInterest = JsonConvert.DeserializeObject<BorannRemapping.Server.Data.AppContext.System[]>(File.ReadAllText("usefullSystems.json"));

            //Console.WriteLine("Loaded " + SystemsOfInterest.Length);
            //SystemsOfInterest = SystemsOfInterest.Where(f => f.InRangeOf(SolReference.Coordinates, 600)).ToArray();
            //Console.WriteLine("Filtered " + SystemsOfInterest.Length);
        }
Esempio n. 10
0
        public void MultiThreadConvertToParty(List <FileInfo> files, DirectoryInfo outputDir)
        {
            filesCount = files.Count;
            uint numThreads = 8;// (uint)Environment.ProcessorCount;
            uint chunk      = (uint)filesCount / numThreads;

            Thread[] threads = new Thread[numThreads];
            for (uint i = 0; i < numThreads; ++i)
            {
                uint chunkStart = i * chunk;
                uint chunkEnd   = chunkStart + chunk;
                if (i == numThreads - 1) // the latest thread should work with all rest files
                {
                    chunkEnd = (uint)filesCount;
                }

                threads[i] = new Thread(() =>
                {
                    for (uint number = chunkStart; number < chunkEnd; number++)
                    {
                        var file           = files[(int)number];
                        var outputFileName = outputDir.FullName + @"\" + ConvertFileNameToParty(file.Name) + ".txt";

                        var hands = SplitHands(File.ReadAllLines(file.FullName).Select(l => l.Trim()).ToList());

                        using (
                            StreamWriter sw =
                                new StreamWriter(new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Write)))
                        {
                            foreach (var hand in hands)
                            {
                                var handParty = hand.ToParty();
                                if (handParty != null)
                                {
                                    foreach (var line in handParty)
                                    {
                                        sw.WriteLine(line);
                                        sw.Flush();
                                    }
                                }
                            }
                        }

                        var convertedFile = new FileInfo(outputFileName);
                        if (convertedFile.Length == 0)
                        {
                            convertedFile.Delete();
                            skippedFilesCount++;
                        }
                        else
                        {
                            convertedFilesCount++;
                        }
                    }
                });
                threads[i].IsBackground = true;
                //threads[i].Start();
            }

            threads.ToList().ForEach(t => t.Start());

            while (threads.Any(t => t.IsAlive))
            {
                var percent = 100 * (skippedFilesCount + convertedFilesCount) / filesCount;
                ConvertProgressBar.Value = (int)percent;
            }
            foreach (var thread in threads)
            {
                thread.Join();
            }
        }
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            int threadCount = 4;     // thread count, set to number of cores in your machine

            long SingleThreadMultipliedOut = 0;
            long ThreadVersion             = 0;
            long TaskVersion = 0;

            Console.WriteLine("");

            Console.WriteLine("Thread Count {0} \n\n", threadCount);

            WorkItem.Initialize();

            //=--------------------------------------------------------------

            //Console.WriteLine("BEGIN loop");
            //sw.Start();
            //for (int i = 0; i < threadCount; i++)
            //{
            //    WorkItem thr = new WorkItem(i.ToString());
            //    thr.DoStuff();
            //}
            //sw.Stop();
            //Console.WriteLine("sw.ElapsedMilliseconds {0}", sw.ElapsedMilliseconds);
            //Console.WriteLine("END loop\n\n");

            //=------ Since the above takes so long estimate it, to see how long this would take on a single core.

            Console.WriteLine("BEGIN loop");
            sw.Start();
            WorkItem thr = new WorkItem("Single ");

            thr.DoStuff();
            sw.Stop();
            SingleThreadMultipliedOut = sw.ElapsedMilliseconds * threadCount;
            Console.WriteLine("sw.Seconds {0,22:#,#.###}", SingleThreadMultipliedOut / 1000);
            Console.WriteLine("END loop\n\n");



            Thread[]   t  = new Thread[threadCount];
            Task[]     ta = new Task[threadCount];
            WorkItem[] at = new WorkItem[threadCount];
            //=--------------------------------------------------------------
            sw.Reset();
            sw.Start();
            Console.WriteLine("BEGIN Tasks");

            at = new WorkItem[threadCount];

            for (int i = 0; i < threadCount; i++)
            {
                //System.Threading.Thread.Sleep(100);
                WorkItem thrx = new WorkItem(i.ToString());
                at[i] = thrx;
                ta[i] = new Task(at[i].DoStuff);
            }

            for (int i = 0; i < threadCount; i++)
            {
                System.Threading.Thread.Sleep(100);
                ta[i].Start();
            }

            while (ta.Any(tx => !tx.IsCompleted))
            {
            }                                             //spin wait

            sw.Stop();
            TaskVersion = sw.ElapsedMilliseconds;
            Console.WriteLine("sw.Seconds {0,22:#,#.###}", TaskVersion / 1000);
            Console.WriteLine("END Tasks\n\n");
            //=--------------------------------------------------------------

            System.Threading.Thread.Sleep(10000);     // sleep for 10 seconds and let the app recover all the resources
            sw.Reset();

            sw.Start();
            Console.WriteLine("BEGIN Threads");

            for (int i = 0; i < threadCount; i++)
            {
                //System.Threading.Thread.Sleep(100);
                WorkItem thrx = new WorkItem(i.ToString());
                at[i] = thrx;
                t[i]  = new Thread(new ThreadStart(at[i].DoStuff));
            }

            for (int i = 0; i < threadCount; i++)
            {
                System.Threading.Thread.Sleep(100);
                t[i].Start();
            }

            while (t.Any(tx => tx.IsAlive))
            {
            }                                       //spin wait - t[0].IsAlive

            sw.Stop();
            ThreadVersion = sw.ElapsedMilliseconds;
            Console.WriteLine("sw.Seconds {0,22:#,#.###}", ThreadVersion / 1000);
            Console.WriteLine("END Threads\n\n");
            //=--------------------------------------------------------------

            Console.WriteLine("\n\nThread Count {0}", threadCount);
            Console.WriteLine("SingleThreadMultipliedOut  sw.Seconds {0,22:#,#.###}", SingleThreadMultipliedOut / 1000);
            Console.WriteLine("ThreadVersion              sw.Seconds {0,22:#,#.###}", ThreadVersion / 1000);
            Console.WriteLine("TaskVersion                sw.Seconds {0,22:#,#.###}", TaskVersion / 1000);
            Console.WriteLine("\n\n");
            //=--------------------------------------------------------------

            Console.WriteLine("Hit Enter To Exit");
            Console.ReadLine();
        }