C++多執行緒安全性,原子程式碼片段,Critical section應用

來源:互聯網
上載者:User

原子程式碼片段,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++多線程非同步呼叫過程中可保證不會出現髒讀和多線程衝突的產生。

 

本文來自網路

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.