8th. Thread Synchronization in user mode (3) _slim read/write lock (SRWLock)

Source: Internet
Author: User

8.5 Slim read/write Lock (SRWLock)--Lightweight read/write lock

(1) Purpose of Srwlock lock

① allows reader threads to access shared resources at the same time (because there is no risk of destroying data)

writes the thread thread executes access to the exclusive resource , and any other thread (including the thread that writes it) waits for the writer thread to access the resource.

(2)How to use Srwlock lock

① initializes the Srwlock structure Initializesrwlock (Psrwlock psrwlock);

② The writer thread calls acquiresrwlockexclusive (Psrwlock)and accesses it in an exclusive way

The reader thread calls acquiresrwlockshared to access it in a shared way

After ③ access is complete, the writer thread calls releasesrwlockexclusive unlock. Reader thread to invoke releasesrwlockshared unlock

④ Note that Srwlock does not need to be deleted and destroyed , so the system will automatically clean up without deleting and so on.

(3) The difference between the Srwlock and the critical section

There are no functions such as TryEnter (shared/exclusive) SRWLock , and if the lock is already occupied, calling Acquiresrwlock (shared/exclusive) blocks the calling thread. (The lock is exclusive when the row is written)

cannot get srwlock recursively, that is, a thread cannot lock the resource multiple times to write to the resource multiple times, and then calls releasesrwlock* multiple times to release the lock.

"Srwlock Program"

#include <windows.h>#include<tchar.h>#include<locale.h>#include<time.h>//////////////////////////////////////////////////////////////////////////Const intg_ithreadcnt = -;intG_iglobalvalue =0;//////////////////////////////////////////////////////////////////////////SRWLOCK G_SL = {0 };//////////////////////////////////////////////////////////////////////////DWORD WINAPI readthread (PVOID pparam);D word WINAPI writethread (PVOID pparam);//////////////////////////////////////////////////////////////////////////int_tmain () {_tsetlocale (Lc_all, _t ("CHS")); Srand ((unsignedint) Time (NULL)); //The read-write lock needs to be initialized, no manual release, and the system will handle itselfInitializesrwlock (&G_SL);    HANDLE athread[g_ithreadcnt]; DWORD dwThreadID=0; System_info si= {0 }; GetSystemInfo (&si);  for(inti =0; I < g_ithreadcnt;i++){        if(0= = rand ()%2) Athread[i]= CreateThread (NULL,0, (lpthread_start_routine) Writethread, NULL, create_suspended,&dwThreadID); ElseAthread[i]= CreateThread (NULL,0, (lpthread_start_routine) Readthread, NULL, create_suspended,&dwThreadID); Setthreadaffinitymask (Athread[i],1<< (i%si.dwnumberofprocessors));    ResumeThread (Athread[i]); }    //wait for all threads to endwaitformultipleobjects (G_ithreadcnt,athread,true,infinite);  for(inti =0; I < g_ithreadcnt;i++) {CloseHandle (athread[i]); } _tsystem (_t ("PAUSE")); return 0;}////////////////////////////////////////////////////////////////////////////////non-protected read and write//DWORD WINAPI readthread (PVOID pparam)//{//_tprintf (_t ("timestamp[%u]:thread[id:0x%x] reads global variable value%d\n"),//GetTickCount (), GetCurrentThreadID (), g_iglobalvalue);//return 0;//}////////////////////////////////////////////////////////////////////////////////DWORD WINAPI writethread (PVOID pparam)//{////for (int i = 0; I <= 4321; i++) {//g_iglobalvalue = i;//        //simulate a long processing process//For (int j = 0; J < K; J + +);//    }////    //Our requirement is that the final value of the write should be 4321, the global variable is not protected//    //where threads may read 0-4321 of the median, this is not the result we want! //_tprintf (_t ("timestamp[%u]:thread[id:0x%x" writes a data value of%d\n "),//GetTickCount (), GetCurrentThreadID (), g_iglobalvalue);//return 0;//}//////////////////////////////////////////////////////////////////////////DWORD WINAPI readthread (PVOID pparam) {//read with shared access__try{acquiresrwlockshared (&G_SL); //The global variables that are read are either 0 or 4321. There's no other value .//when the read thread 1th is dispatched, it reads 0. But once the write thread is dispatched, all subsequent//The value read will be 4321_tprintf (_t ("timestamp[%u]:thread[id:0x%x] Read global variable value is%d\n"), GetTickCount (), GetCurrentThreadID (), g_iglobalvalue); } __finally{releasesrwlockshared (&G_SL); }    return 0;}//////////////////////////////////////////////////////////////////////////DWORD WINAPI writethread (PVOID pparam) {//write it in the same way__try{acquiresrwlockexclusive (&G_SL);  for(inti =0; I <=4321; i++) {G_iglobalvalue=i; SwitchToThread (); //deliberately switching to another thread, it's obvious//during this cycle, because of the way it is discharged//so the other access lock threads will be suspended//so that it cannot be read or written.         }        //Our requirement is that the final value of the write should be 4321, the global variable is not protected//where threads may read 0-4321 of the median, this is not the result we want! _tprintf (_t ("Timestamp[%u]:thread[id:0x%x] Writes the data value to%d\n"), GetTickCount (), GetCurrentThreadID (), g_iglobalvalue); } __finally{releasesrwlockexclusive (&G_SL); }    return 0;}

(4) Comparison of Srwlock lock with other locks

8th. Thread Synchronization in user mode (3) _slim read/write lock (SRWLock)

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: info-contact@alibabacloud.com 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.