之前曾经写过一个关于多线程开发的文章,但是经过大量测试后发现,如果需要调用同一个资源的最好方法就是加上信号量(这个是操作系统中的概念),用它来实现线程和线程之间的互斥,从而达到该资源只会被单一线程使用。
以下就是实例代码,各位也可以到微软的官方网站上获得,我只是做了少许修改
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace multiThread
{
class program
{
// A semaphore that simulates a limited resource pool.
//
private static Semaphore _pool;
// A padding interval to make the output more orderly.
private static int _padding;
public static void Main()
{
// Create a semaphore that can satisfy up to three
// concurrent requests. Use an initial count of zero,
// so that the entire semaphore count is initially
// owned by the main program thread.
//
_pool = new Semaphore(0, 1);
// Create and start five numbered threads.
//
for (int i = 1; i <= 20; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(Worker));
// Start the thread, passing the number.
//
Thread.Sleep(500);
t.Start(i);
}
// Wait for half a second, to allow all the
// threads to start and to block on the semaphore.
//
Thread.Sleep(500);
// The main thread starts out holding the entire
// semaphore count. Calling Release(3) brings the
// semaphore count back to its maximum value, and
// allows the waiting threads to enter the semaphore,
// up to three at a time.
//
Console.WriteLine("Main thread calls Release(3).");
_pool.Release(1);
Console.WriteLine("Main thread exits.");
Console.ReadLine();
}
private static void Worker(object num)
{
// Each worker thread begins by requesting the
// semaphore.
Console.WriteLine("Thread {0} begins " +
"and waits for the semaphore.", num);
_pool.WaitOne();
// A padding interval to make the output more orderly.
int padding = Interlocked.Add(ref _padding, 100);
Console.WriteLine("Thread {0} enters the semaphore. {1}", num, DateTime.Now.ToString("yyyyMMddHHmmssfff"));
// The thread's "work" consists of sleeping for
// about a second. Each thread "works" a little
// longer, just to make the output more orderly.
//
//Thread.Sleep(1000 + padding);
Thread.Sleep(500);
Console.WriteLine("Thread {0} releases the semaphore.", num);
Console.WriteLine("Thread {0} previous semaphore count: {1}",
num, _pool.Release());
}
}
}
转载于:https://www.cnblogs.com/lx0831/archive/2008/11/19/1336618.html