pre-emptive multithreading web spider

原创 2001年08月20日 17:30:00

pre-emptive multithreading web spider

this article was contributed by sim ayers.

the win32 api supports applications that are pre-emptively multithreaded. this is a very useful and powerful feature of win32 in writing mfc internet spiders. the spider project is an example of how to use preemptive multithreading to gather information on the web using a spider/robot with the mfc wininet classes.

this project produces a spidering software program that checks web sites for broken url links. link verification is done only on href links. it displays a continously updated list of urls in a clistview that reports the status of the href link. the project could be used as a template for gathering and indexing information to be stored in a database file for queries.

search engines gather information on the web using programs called robots. robots (also called web crawlers, spiders, worms, web wanderers, and scooters) automatically gather and index information from around the web, and then put that information into databases. (note that a robot will index a page, and then follow the links on that page as a source for new urls to index.) users can than construct queries to search these databases to find the information they want.

by using preemptive multithreading, you can index a web page of url links, start a new thread to follow each new url link for a new source of urls to index.

the project uses the mdi cdocument used with a custom mdi child frame to display a ceditview when downloading web pages and a clistview when checking url links. the project also uses the cobarray, cinternetsession, chttpconnection, chttpfile, and cwinthread mfc classes. the cwinthread class is used to produce multiple threads instead of using the asynchronous mode in cinternetsession, which is realy left over from the winsock 16 bit windows platform.

the spider project uses simple worker threads to check url links or download a web page. the cspiderthread class is derived from the cwinthread class so each cspiderthread object can use the cwinthread message_map() function. by declaring a "declare_message_map()" in the cspiderthread class the user interface is still responsive to user input. this means you can check the url links on one web server and at the same time download and open a web page from another web server. the only time the user interface will become unresponsive to user input is when the thread count exceedes maximum_wait_objects which is defined as 64.

in the constructor for each new cspiderthread object we supply the threadproc function and the thread paramters to be passed to the threadproc function.

	cspiderthread* pthread;
	pthread = null;
	pthread = new cspiderthread(cspiderthread::threadfunc,pthreadparams); // create a new cspiderthread object

in the cspiderthread constructor we set the cwinthread* m_pthread pointer in the thread paramters structure so we can point to the correct instance of this thread;

pthreadparams->m_pthread = this;

the cspiderthread threadproc function

// simple worker thread proc function
uint cspiderthread::threadfunc(lpvoid pparam)
	threadparams * lpthreadparams = (threadparams*) pparam;
	cspiderthread* lpthread = (cspiderthread*) lpthreadparams->m_pthread;

	// use  sendmessage instead of postmessage here to keep the current thread count
	// synchronizied. if the number of threads is greater than maximum_wait_objects (64)
	// the program will be come	 unresponsive to user input

		wm_user_thread_done, 0, (lparam)lpthreadparams);  // deletes lpthreadparams and decrements the thread count

	return 0;

the structure passed to the cspiderthread threadproc function

typedef struct tagthreadparams
	hwnd m_hwndnotifyprogress;
	hwnd m_hwndnotifyview;
	cwinthread* m_pthread;
	cstring m_pszurl;
	cstring m_contents;
	cstring m_strservername;
	cstring m_strobject;
	cstring m_checkurlname;
	cstring m_string;
	dword m_dwservicetype;
	dword  m_threadid;
	dword m_status;
	urlstatus m_pstatus;
	internet_port  m_nport;
	int m_type;
	bool m_rootlinks;


after the cspiderthread object has been created we use the creatthread function to start the execution of the new thread object.

	if (!pthread->createthread())   //  starts execution of a cwinthread object
		afxmessagebox("cannot start new thread");
		delete pthread;
		pthread = null;
		delete pthreadparams;
		return false;

once the new thread is running we use the ::sendmessage function to send messages to the cdocument's-> clistview with the status structure of the url link.

	if(pthreadparams->m_hwndnotifyview != null)
		::sendmessage(pthreadparams->m_hwndnotifyview,wm_user_check_done, 0, (lparam) &pthreadparams->m_pstatus);

sturcture used for url status.

typedef struct tagurlstatus
	cstring m_url;
	cstring m_urlpage;
	cstring m_statusstring;
	cstring m_lastmodified;
	cstring m_contenttype;
	cstring m_contentlength;
	dword	m_status;
}urlstatus, * purlstatus;

each new thread creats a new cmyinternetsession (derived from cinternetsession) object with enablestatuscallback set to true, so we can check the status on all internetsession callbacks. the dwcontext id for callbacks is set to the thread id.

bool cinetthread::initserver()
		m_psession = new cmyinternetsession(agentname,m_nthreadid);
		int ntimeout = 30;  // very important, can cause a server time-out if set to low
							// or hang the thread if set to high.
		the time-out value in milliseconds to use for internet connection requests. 
		if a connection request takes longer than this timeout, the request is canceled.
		the default timeout is infinite. */
		m_psession->setoption(internet_option_connect_timeout,1000* ntimeout);
		/* the delay value in milliseconds to wait between connection retries.*/
		/* the retry count to use for internet connection requests. if a connection 
		attempt still fails after the specified number of tries, the request is canceled.
		the default is five. */

	catch (cinternetexception* pex)
		// catch errors from wininet
		m_psession = null;
		return false ;

	return true;

the key to using the mfc wininet classes in a single or multithread program is to use a try and catch block statement surrounding all mfc wininet class functions. the internet is very unstable at times or the web page you are requesting no longer exist, which is guaranteed to throw a cinternetexception error.

		// some mfc wininet class function
	catch (cinternetexception* pex)
		// catch errors from wininet
		return false ;

the maximum count of threads is initially set to 64, but you can configure it to any number between 1 and 100. a number that is too high will result in failed connections, which means you will have to recheck the url links.

a rapid fire succession of http requests in a /cgi-bin/ directory could bring a server to it's knees. the spider program sends out about 4 http request a second. 4 * 60 = 240 a minute. this can also bring a server to it's knees. be carefull about what server you are checking. each server has a server log with the requesting agent's ip address that requested the web file. you might get some nasty email from a angry web server administrator.

you can prevent any directory from being indexed by creating a robots.txt file for that directory. this mechanism is usually used to protect /cgi-bin/ directories. cgi scripts take more server resources to retrieve.

when the spider program checks url links it's goal is to not request too many documents too quickly. the spider program adheres somewhat to the standard for robot exclusion. this standard is a joint agreement between robot developers, that allows www sites to limit what url's the robot requests. by using the standard to limit access, the robot will not retrieve any documents that web server's wish to disallow.

before checking the root url, the program checks to see if there is a robots.txt file in the main directory. if the spider program finds a robots.txt file the program will abort the search. the program also checks for the meta tag in all web pages. if it finds a meta name="robots" content ="noindex,nofollow" tag it will not index the urls on that page.

windows 95
mfc/vc++ 5.0
wininet.h dated 9/25/97
wininet.lib dated 9/16/97
wininet.dll dated 9/18/97

can't seem to keep the thread count below 64 at all times.
limit of 32,767 url links in the clistview
wouldn't parse all urls correctly, will crash program occasionally using cstring functions with complex urls.

internet tools - fred forester
multithreading applications in win32
win32 multithreaded programming

download source code and example (65 kb)

last updated: 21 june 1998

pre-emptive multithreading web spider

2001年08月20日 17:30:00 pre-emptive multithreading web spider this article was contributed by sim ...
  • softart
  • softart
  • 2007年10月27日 08:05
  • 158

pre-emptive multithreading web spider铪铪铪

 pre-emptive multithreading web spider this article was contributed by sim ayers. the win32 api su...
  • hejishan
  • hejishan
  • 2008年03月11日 10:04
  • 240


Android系统的性能优化,是一个很重要的课题。要优化系统性能,首先应该有一些对系统进行分析的的工具。在这里将介绍几个常用的工具。随着后续的深入,会有新的工具加入。工具:    1、GProfile...
  • dongjun7357
  • dongjun7357
  • 2011年03月22日 17:44
  • 4080


1.FreeSpider是Lazarus CGI程序的开发组件。有点类似Delphi的WebSnap。参考地址:
  • penker_zhao
  • penker_zhao
  • 2010年05月10日 16:03
  • 898


Starting a New Thread To spawn anotherthread, you need to call following method available in thread ...
  • Mybigkid
  • Mybigkid
  • 2017年10月22日 21:44
  • 256


  • rztyfx
  • rztyfx
  • 2014年04月27日 13:59
  • 712

CodeForces 270B - Multithreading

Emuskald is addicted to Codeforces, and keeps refreshing the main pagenot to miss any changes in the...
  • leifjacky
  • leifjacky
  • 2015年07月29日 00:19
  • 425

【Codeforces Beta Round #26 】Codeforces 26E Multithreading

  • sdfzyhx
  • sdfzyhx
  • 2017年05月01日 23:07
  • 116

c++ g++运行出现Enable multithreading to use std::thread: Operation not permitted解决

使用了c++11的thread库,运行出现了: terminate called after throwing an instance of 'std::system_error'   what(...
  • xyblog
  • xyblog
  • 2016年01月11日 22:30
  • 3063


爬虫(Spider),反爬虫(Anti-Spider),反反爬虫(Anti-Anti-Spider),这之间的斗争恢宏壮阔... Day 1 小莫想要某站上所有的电影,写了标准的爬虫(基于Ht...
  • zoubf
  • zoubf
  • 2016年03月24日 22:33
  • 1889
您举报文章:pre-emptive multithreading web spider