Key Section of the multi-threaded Series II

Source: Internet
Author: User

When we process thread synchronization in a complex situation, such as adding or deleting a list, the atomic operation cannot meet our needs. You can try the key segment. The key segment is very easy to use. It also uses the interlocked function internally, so the speed is very fast. The biggest drawback of a key segment is that it is not possible to synchronize threads among multiple processes.

Key SectionOfUseYesFirstDefinitionOneStructVariableCritical_section,Then use the Function

void WINAPI InitializeCriticalSection(  __out  LPCRITICAL_SECTION lpCriticalSection);


You must call a function before accessing protected resources.

Void winapi entercriticalsection (_ inout maid );Entercriticalsection checks the member variables in the struct, which indicate whether a thread is accessing the resource and which thread is accessing the resource.
You need to call the function after completing the operations on shared resources.
Void winapi leavecriticalsection (_ inout lpcritical_section lpcriticalsection); call the void winapi deletecriticalsection (_ inout lpcritical_section lpcriticalsection) when protection for shared resources is not required ); to delete the key segment object and release all system resources it uses.(Csdn's edited articles have various inexplicable format problems, causing headaches) encapsulate classes to implement key segments.
# Pragma once # include "stdafx. H" class criticalsection {public: criticalsection (){}~ Criticalsection () {deletecriticalsection (& CS);} inline bool initcriticalsection () {bool bresult = true ;__ try {initializecriticalsection (& CS); // The function fails, very unlikely }__ T (exception_execute_handler) {bresult = false;} return bresult;} inline void entersection () {entercriticalsection (& CS ); // The possibility of exceptions thrown by this function is also very low} inline void leavesection () {leavecriticalsection (& CS);} PRIVATE: critical_section Cs ;};

The main program defines a list container, a thread that adds 10 elements each time, and a thread that deletes the first five elements each time.

// Critical_section.cpp: defines the entry point of the console application. // # Include "stdafx. H "# include" lock. H "typedef unsigned (_ stdcall * pythread) (void *); volatile long bstop = false; criticalsection; List <int> ilist; DWORD addthread (lpvoid LP) {While (interlockedcompareexchange (& bstop, 1, 1 )! (= 1) {sleep (100); criticalsection. entersection (); // Add 10 random numbers for (INT I = 0; I <10; ++ I) {int inum = rand () % 10000; ilist. push_back (inum);} // output the cout value in the current container before each exit of the key segment <"Delete the list before the first five digits" <Endl; copy (ilist. begin (), ilist. end (), ostream_iterator <int> (cout, ","); cout <Endl; criticalsection. leavesection ();} return 0;} DWORD deletethread (lpvoid LP) {While (interlockedcompareexchange (& bstop, 1, 1 )! (= 1) {sleep (100); criticalsection. entersection (); If (ilist. empty () {criticalsection. leavesection (); continue;} // The first five elements in the container are deleted each time. For (INT I = 0; I <5; ++ I) {ilist. pop_front () ;}// output the current container value cout <"Delete the list of the first five digits" <Endl; copy (ilist. begin (), ilist. end (), ostream_iterator <int> (cout, ","); cout <Endl; criticalsection. leavesection ();} return 0;} int _ tmain (INT argc, _ tchar * argv []) {If (! Criticalsection. initcriticalsection () // initialize return-1 in the main function; srand (unsigned) time (0); handle hthreads [2]; hthreads [0] = (handle) _ beginthreadex (null, 0, (pythread) addthread, null, 0, null); hthreads [1] = (handle) _ beginthreadex (null, 0, (pythread) deletethread, null, 0, null); sleep (1000); interlockedexchange (& bstop, true); waitformultipleobjects (2, hthreads, true, infinite ); cout <"both threads exit" <Endl; return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

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.