原子程式碼片段,Critical section 使用方法
使用方法
Example Code For Critical Sections with Win32 API</p><p>/* Sample C/C++, Windows, link to kernel32.dll */<br />//在windows平台下,調用了kernel32.dll的windows API函數<br />#include <windows.h></p><p>static CRITICAL_SECTION cs;<br />/* This is the critical section object -- once initialized,it cannot be moved in memory */<br />/* If you program in OOP, declare this in your class */</p><p>/* Initialize the critical section before entering multi-threaded context. */<br />//在你進入多線程調用前,需要調用這個函數進行初始化<br />InitializeCriticalSection(&cs);</p><p>void f()<br />{<br /> /* Enter the critical section -- other threads are locked out */<br /> //進入原子程式碼片段,不可分割程式碼片段,鎖死其他線程,使其他線程不會進入。<br /> EnterCriticalSection(&cs);</p><p> /* Do some thread-safe processing! */<br /> //在這段代碼中線程不會中斷直到執行完畢</p><p> /* Leave the critical section -- other threads can now EnterCriticalSection() */<br /> //離開原子程式碼片段。其他線程才個進入<br /> LeaveCriticalSection(&cs);<br />}</p><p>/* Release system object when all finished -- usually at the end of the cleanup code */<br /> //釋放系統對象。一般用在代碼結束的時候。<br />DeleteCriticalSection(&cs);</p><p>
這段代碼是保護C++多執行緒安全性的代碼。
在C++多線程非同步呼叫過程中可保證不會出現髒讀和多線程衝突的產生。
本文來自網路