-
线程同步:旗语(Semaphore)
线程同步:旗语(Semaphore) 收藏
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- using System.Threading;
- using System.Diagnostics;
-
-
-
-
- namespace ThreadStudy2
- {
- class Program
- {
- static void Main(string[] args)
- {
- int threadCount = 6;
- int semaphoreCount = 4;
-
- Semaphore semaphore = new Semaphore(semaphoreCount,semaphoreCount);
- Thread[] threads = new Thread[threadCount];
- for (int i = 0; i < threadCount; i++)
- {
- threads[i] = new Thread(ThreadMain);
- threads[i].Start(semaphore);
- }
- for (int i = 0; i < threadCount; i++)
- {
- threads[i].Join();
- }
- Console.WriteLine("All threads finished");
- Console.Read();
-
- }
- static void ThreadMain(object o)
- {
-
-
-
- Semaphore semaphore = o as Semaphore;
- Trace.Assert(semaphore != null, "o must be a Semaphore type");
- bool isCompleted = false;
- while (!isCompleted)
- {
- if (semaphore.WaitOne(600, false))
- {
- try
- {
- Console.WriteLine("Thread {0} locks the sempahore",Thread.CurrentThread.ManagedThreadId);
- Thread.Sleep(2000);
- }
- finally
- {
- semaphore.Release();
- Console.WriteLine("Thread {0} releases the semaphore ",Thread.CurrentThread.ManagedThreadId);
- isCompleted = true;
- }
- }
- else
- {
- Console.WriteLine("Timeout for thread {0} ; wait again", Thread.CurrentThread.ManagedThreadId);
- }
- }
- }
-
-
-
- }
- }
-
相关阅读:
支持向量机SVM知识点概括
决策树知识点概括
HDU 3081 Marriage Match II
HDU 3572 Task Schedule
HDU 4888 Redraw Beautiful Drawings
Poj 2728 Desert King
HDU 3926 Hand in Hand
HDU 1598 find the most comfortable road
HDU 4393 Throw nails
POJ 1486 Sorting Slides
-
原文地址:https://www.cnblogs.com/sunwei2012/p/1868280.html
Copyright © 2020-2023
润新知