Nik*_*las 1 c# multithreading semaphore threadpool
示例线程池:
public class Example {
public static void Main() {
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); //task 1
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); //task 2
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); //task 3
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
static void ThreadProc(Object stateInfo) {
Console.WriteLine("Hello from the thread pool.");
}
}
Run Code Online (Sandbox Code Playgroud)
示例信号量:
public class Example
{
private static Semaphore _pool;
private static int _padding;
public static void Main()
{
_pool = new Semaphore(0, 3);
// Create and start five numbered threads.
//
for(int i = 1; i <= 5; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(Worker));
t.Start(i);
}
Thread.Sleep(500);
Console.WriteLine("Main thread calls Release(3).");
_pool.Release(3);
Console.WriteLine("Main thread exits.");
}
private static void Worker(object num)
{
Console.WriteLine("Thread {0} begins " +
"and waits for the semaphore.", num);
_pool.WaitOne();
int padding = Interlocked.Add(ref _padding, 100);
Console.WriteLine("Thread {0} enters the semaphore.", num);
Thread.Sleep(1000 + padding);
Console.WriteLine("Thread {0} releases the semaphore.", num);
Console.WriteLine("Thread {0} previous semaphore count: {1}",
num, _pool.Release());
}
}
Run Code Online (Sandbox Code Playgroud)
我想它是Semaphore的一些开销,在这个例子中创建5个线程,但是线程池使用内置的"threadpool"(它将使用像backgroundworker这样的现有线程).这是正确的还是更多,使用信号量是否有任何真正的优势,如果你只是想要一个简单的线程池,但速度和性能是一个问题?
你正在比较苹果和奶牛.
ThreadPool允许将Threads用于小任务.它没有任何方便的rendez-vous机制(你的Sleep(1000)是解决这个问题的一个弱解决方案).
信号量是一种同步线程的方法,它们可以是ThreadPool线程.
| 归档时间: |
|
| 查看次数: |
3301 次 |
| 最近记录: |