CRITICAL_SECTION   gCS;   
InitializeCriticalSection(&gCS); 
EnterCriticalSection(&gCS); 
LeaveCriticalSection(&gCS); 
DeleteCriticalSection(&gCS); 
/////////////////////////////////////一个方法实现代码:void CTest::Test()
{
 EnterCriticalSection(&gCS); 
  for(;;)
  {
      if(true)
      {
          EnterCriticalSection(&gCS); 
          ............
          LeaveCriticalSection(&gCS);  
      }
  }
 LeaveCriticalSection(&gCS);       
}可以这样用吗?

解决方案 »

  1.   

    当然有意义,如果我锁的一个list.一边访问,一般删除,我程序就这样用的
      

  2.   

    http://topic.csdn.net/t/20030605/17/1880545.html
      

  3.   


    那就需要两个锁,一个锁外部的, 一个锁list
      

  4.   

    用两个锁不就行了------------------------------------
    Posted By EasyCsdn1.0
      

  5.   

    没问题,重复Enter,只要也同样次数的重复Leave就行了。CriticalSection结构里面有计数的。
      

  6.   

    你要实现的是什么?临界区应该是与要加锁的资源相对应的,一个或一组资源用一个临界区,同一线程重复Enter同一临界区没有意义。
      

  7.   

    多个线程,对同一个list操作,有的线程要查询和删除
      

  8.   

    我个人认为是不行的,除非你有两个关键代码段,我不知道EnterCriticalSection(&gCS); 后再来个EnterCriticalSection(&gCS); 和LeaveCriticalSection(&gCS);后再来个LeaveCriticalSection(&gCS);会是什么作用,或许这种用法本身就是错的。
      

  9.   

    这是可以的,但enter和leave必须成对,一个线程最外层的临界区leave后,其他线程才可以进入。
      

  10.   

    From msdn:After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. The thread enters the critical section each time EnterCriticalSection and TryEnterCriticalSection succeed. A thread must call LeaveCriticalSection once for each time that it entered the critical section.