今天发现自己工程里同步使用CRITICAL_SECTION变量的地方根本就没有锁住,
InitializeCriticalSection( )变量后,不管多少次EnterCriticalSection( )都能进去调试很久不知道是哪里的问题,写了个最简单的测试程序(win32控制台程序,使用mfc库),
还是有问题.测试程序如下#include "stdafx.h"
#include "testLock.h"#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endifCWinApp theApp;
using namespace std;int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0; // initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CString strHello;
strHello.LoadString(IDS_HELLO);
cout << (LPCTSTR)strHello << endl;
} CRITICAL_SECTION Sec;
InitializeCriticalSection( &Sec );

EnterCriticalSection( &Sec );   ///能调用返回,返回后
                                         ///Sec.LockCount=0,RecursionCount=1 EnterCriticalSection( &Sec );   ///还是能返回,没招,返回后
                                         ///Sec.LockCount=1,RecursionCount=2 return nRetCode;
}有经验的大侠指点下,不胜感激~~

解决方案 »

  1.   

    CRITICAL_SECTION CriticalSection; // Initialize the critical section.
    InitializeCriticalSection(&CriticalSection); // Request ownership of the critical section.
    __try 
    {
        EnterCriticalSection(&CriticalSection);     // Access the shared resource.
    }
    __finally 
    {
        // Release ownership of the critical section.
        LeaveCriticalSection(&CriticalSection);    // Release resources used by the critical section object.
        DeleteCriticalSection(&CriticalSection)
    }
      

  2.   

    都不理解CRITICAL_SECTION 用来什么的. 所谓CRITICAL_SECTION 是用来处理"一份被共享的资源", 如一段内存, 一个数据结构,一个文件等.也就是资源每一次,同一个时间只能被一个线程处理.简单的讲, CRITICAL_SECTION 用来保护资源, 当一个线程对某资源A写的时候, 避免别的线程对资源A进行任何操作. 就是保护数据的一致性.你刚刚用的在同一线程. 没有用...多线程才使用..
      

  3.   

    嗯,同意上面的观点,CRITICAL_SECTION是在多线程的编程中使用
      

  4.   

    对,CRITICAL_SECTION
    是在进行线程同步或者进程同步时才用的内核对象。