How does the system know that global variables, local static variables, or local static objects can only be constructed once?

1. For example: In a single thread: Because objx is a static object, there will be its space in the data area. There is a four-byte space at the address above or below it to mark whether objx is created.

  • First, the first mark is 0, which means objx has not been created.

 

  • When executing the statement that creates a static object, the system will query the tag value. If the tag value is 0, the constructor is called to create objx and the tag value is changed to 1.

 

  •  When the statement to create a static object is executed again, the tag value is queried. If the tag value is 1, the constructor will not be called again to create the objx object, and the system ensures that the static object is only created once.

2. In multi-threading, both the thread functions funa and funb are calling the GetObject() function to create objx. When funa is reading the tag value of objx, if the value is 0, objx is created. At the same time, the funb thread is also reading the tag value of objx. At this time, the value has not changed and is still 0, so objx may be created twice. The problem caused by the static object objx being created twice is that thread funb will overwrite the value of objx initialized by thread funa.

 Because this mark value is maintained by the system, we cannot use a mutex to protect this mark value, but we can lock the thread, lock the thread when funa is executed, unlock it after the execution, and then execute the thread funb . It is guaranteed that when funa is executed, the mark value of objx is changed to 1. When funb is executed, the mark value is read as 1, and the objx static object will not be created twice.

 

Guess you like

Origin blog.csdn.net/weixin_53472334/article/details/131989299
Recommended