use*_*333 5 c# queue multithreading web-crawler producer-consumer
我需要抓取父网页及其子网页,我从http://www.albahari.com/threading/part4.aspx#%5FWait%5Fand%5FPulse跟踪生产者/消费者概念.另外,我使用5个线程将链接排队和出列.
有关如何在队列长度未知的情况下,如果所有线程都已完成处理队列,我将如何结束/加入所有线程?
以下是关于我如何编码的想法.
static void Main(string[] args)
{
//enqueue parent links here
...
//then start crawling via threading
...
}
public void Crawl()
{
//dequeue
//get child links
//enqueue child links
}
Run Code Online (Sandbox Code Playgroud)
您可以在末尾加入一个虚拟令牌,并让线程在遇到此令牌时退出。喜欢:
public void Crawl()
{
int report = 0;
while(true)
{
if(!(queue.Count == 0))
{
if(report > 0) Interlocked.Decrement(ref report);
//dequeue
if(token == "TERMINATION")
return;
else
//enqueue child links
}
else
{
if(report == num_threads) // all threads have signaled empty queue
queue.Enqueue("TERMINATION");
else
Interlocked.Increment(ref report); // this thread has found the queue empty
}
}
}
Run Code Online (Sandbox Code Playgroud)
当然,我省略了enqueue/dequeue操作的锁。
| 归档时间: |
|
| 查看次数: |
721 次 |
| 最近记录: |