libxml2 多线程使用

libxml2官方网站如是说:

Starting with 2.4.7, libxml2 makes provisions to ensure that concurrent threads can safely work in parallel parsing different documents. There is however a couple of things to do to ensure it:

  • configure the library accordingly using the --with-threads options
  • call xmlInitParser() in the "main" thread before using any of the libxml2 API (except possibly selecting a different memory allocator)

以下摘自: http://blog.csdn.net/Gavin_Han/article/details/1795032

   使用xmlCleanupParser()必须遵循一下两个原则:

   (1) xmlCleanupParser()不能在线程中被调用,因为先结束的进程会把共享内存清除,接下来尚未结束的的线程就无法正确访问.

   (2) xmlCleanupParser()应该在主线程中被调用,在不再使用libxml2库时,一般在程序的出口处.

   这里需要注意一个问题,如果你无法确定其他用户是否还在使用libxml2库,那么就不要调用xmlCleanupParser(),因为这样最差的情况是浪费了一块内存,直至在程序结束时才能被收回,比起程序崩溃,这样的代价还是值得的.在mailing list中,作者也提到这样的方案.

   同样,在进程(所有进程结束之后)多次调用xmlCleanupParser()不会对程序产生任何影响,第二次以后的调用仅是检查标志位和简单第返回.

 在多线程环境下,推荐的使用方法是:

   ------------------------------------------------------------------------------

  int main ( int argc, char **argv )
  {
   //do library initialization at the beginning of the program
   xmlInitParser();
 
   //do other program initialization
   
 
    //start thread
   for (i = 0; i < num_threads; i++) {
      ret = pthread_create
     
     …
   }
 
   //do other program initialization
   …
 
   //do library cleanup when the program ends up
   xmlCleanupParser(();
 
   return 0;

 }  

 ------------------------------------------------------------------------------ 

posted on 2011-10-25 19:03  foreveryl  阅读(962)  评论(0编辑  收藏  举报