Win32中进程和线程的协调工作是由同步机制(synchronous mechanism)来完成的。
Critical Sections(关键区域、临界区域)
重点:
一旦一个线程进入一个critical section,他就能够一而再的重复进入critical section。每个进入操作,必须对应一个离开的操作。
千万不要再一个critical section中调用Sleep或任何Wait等API函数。
critical section不是核心对象,如果进入critical section的线程结束或者当掉了 ,而没有离开criticalsection的话,系统无法将此critical section清楚掉。如果需要此机能,应该使用mutex。
基本知识:
它是指一小块“用来处理一份被共享之资源” 的程序代码。一次只能有一个线程进入critical section中。实施的方式是在程序中加上“进入”或者“离开”critical section的操作。critical section并不是核心对象,所以没有句柄handle,其与核心对象不同,它存在于进程的内存空间中。需要做的是定义一个CRITICAL_SECTION的变量,使用InitializeCriticalSection()进行初始化。
Initializes a critical section object.
void WINAPI InitializeCriticalSection(
__out LPCRITICAL_SECTION lpCriticalSection
);
Parameters
lpCriticalSection : A pointer to the critical section object.
Return Value:
This function does not return a value.
Windows Server 2003 and Windows XP/2000: In low memory situations, InitializeCriticalSection can raise a STATUS_NO_MEMORY exception. This exception was eliminated starting with Windows Vista.
void WINAPI InitializeCriticalSection(
__out LPCRITICAL_SECTION lpCriticalSection
);
Parameters
lpCriticalSection : A pointer to the critical section object.
Return Value:
This function does not return a value.
Windows Server 2003 and Windows XP/2000: In low memory situations, InitializeCriticalSection can raise a STATUS_NO_MEMORY exception. This exception was eliminated starting with Windows Vista.
用完critical section后,要使用DeleteCriticalSection()释放。
Releases all resources used by an unowned critical section object.
void WINAPI DeleteCriticalSection(
__in_out LPCRITICAL_SECTION lpCriticalSection
);
Parameters
lpCriticalSection :A pointer to the critical section object. The object must have been previously initialized with the InitializeCriticalSection function.
Return Value:
This function does not return a value.
void WINAPI DeleteCriticalSection(
__in_out LPCRITICAL_SECTION lpCriticalSection
);
Parameters
lpCriticalSection :A pointer to the critical section object. The object must have been previously initialized with the InitializeCriticalSection function.
Return Value:
This function does not return a value.
一旦critical section被初始化,那么每个线程可以进入其中,通过EnterCriticalSection函数。
Waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.
void WINAPI EnterCriticalSection(
__in_out LPCRITICAL_SECTION lpCriticalSection
);
Parameters
lpCriticalSection :A pointer to the critical section object.
void WINAPI EnterCriticalSection(
__in_out LPCRITICAL_SECTION lpCriticalSection
);
Parameters
lpCriticalSection :A pointer to the critical section object.
线程离开缓冲区使用LeaveCriticalSection函数
Releases ownership of the specified critical section object.
void WINAPI LeaveCriticalSection(
__in_out LPCRITICAL_SECTION lpCriticalSection //A pointer to the critical section object.
);
void WINAPI LeaveCriticalSection(
__in_out LPCRITICAL_SECTION lpCriticalSection //A pointer to the critical section object.
);