Wednesday, July 24, 2013

Where is static variable used? A live Example


Till Date this was the question asked in many 'C' programming interviews asking for a live case of static variable, have come across a few cases but nothing was a solid one. Recently while going through spinlock code came across this function used in lockdep which has a solid example of static variable usage.


First, a little background on the context of lockdep and on below function. Lockdep is a lock monitoring utility in the kernel (an userspace version exists too) which keep tracks of all the locks allocated and order in which they are taken and throw necesary warnings if things are wrong.


Refer Introduction to LOCKDEP for details.


Now how do we track these numerous locks in the kernel, we wont. We only track the lock initialization per data structure, any number of the locks taken on the data structure doesnt matter unless we track one remaining show same behavior. With that we need to have a unique ID to identify a lock/data structure


a) If the lock is allocated statically (stack), then we use the address of the lock as the Unique ID (UID)


b) If the lock is allocated dynamically (heap), then we cant use the address as there will be too many addresses


So here's where the "static" comes in, in every lock init we use a "static" variable (its address a UID) so that across the initialization of the same structure the address remains the same.

       # define spin_lock_init(lock) \ 
       do { \ 
           static struct lockdep_type_key __key; \ 
           __spin_lock_init((lock), #lock, &__key); \ 
       } while (0)


Hmm, beauty isn't it. Finally a live use case for static variable, at least which i know :-)


1 comment:

  1. No Deposit Casino Bonus Codes - 100's of Casino Bonus
    No deposit 가입시 꽁 머니 환전 bonus codes in online 메이플 캐릭터 슬롯 casinos allow you 포커 to 양방배팅 play at low-risk casino games, using no deposit free spins. You can take advantage of no deposit 김해 휴게텔 bonus codes

    ReplyDelete