Quickly build the MMO Server framework (5) Things About Timer

Source: Internet
Author: User

Timer management is often an optimization hotspot in systems such as MMO servers that need to process a large number of transactions.
The simplest round-robin timer implementation is as follows (psudo code ):
Class player <br/>{< br/> Public: <br/> void loop () <br/>{< br/> If (timer. check () <br/>{< br/> // do something; <br/>}< br/> // other timer... <br/>}< br/> PRIVATE: <br/> timer; <br/>}< br/> void main () <br/>{< br/> while (true) <br/>{< br/> foreach player in playermanager <br/>{< br/> player. loop (); <br/>}< br/> sleep (0); <br/>}< br/>}; <br/>
The only benefit of this design is the simplicity of programming.
Disadvantages:
When a large number of timers need to be detected increase, the overall performance will seriously decline. Even if you manually add a method that filters out low-precision timers with high precision, it is easy to cause logical processing to accumulate at a certain point in time.
Induce bad styles of logic code accumulation in loop () functions.
Containers such as playermanager should always prevent the addition or deletion of elements in the traversal process from invalidating the iterator, but this is another problem.

For servers, the main difference between the timer logic and the client is that the main operation on the client is graphical rendering, and most objects must be updated at each frame, the addition of the timer scheduling mechanism for these objects may not be worth the candle; the logic for long time intervals is relatively small, and the unified round robin processing is acceptable. The server processes large batches of transactions at intervals of more than a second. Polling will result in a large amount of idling of CPU. Furthermore, if the transaction logic cannot be well isolated, the object's update function will be filled with various types of Code such as if (Task & tasktimer. Check (), which is ugly and inefficient.

In boost, deadline_timer class is provided in combination with io_service. The synchronization timer will cause blocking, which is of little use and will not be referenced here. The following is an example of an asynchronous Timer: (from the boost Documentation)
// <Br/> // timer. cpp <br/> //~~~~~~~~~ <Br/> // copyright (c) 2003-2008 Christopher M. kohlhoff (Chris at kohlhoff dot com) <br/> // distributed under the boost software license, Version 1.0. (See accompanying <br/> // file license_00000.txt or copy at http://www.boost.org/LICENSE_1_0.txt) <br/> // <br/> # include <iostream> <br/> # include <boost/ASIO. HPP> <br/> # include <boost/date_time/posix_time/posix_time.hpp> <br/> void print (Const boost: System: error_code &/* E */) <br/>{< br/> STD: cout <"Hello, world! /N "; <br/>}< br/> int main () <br/>{< br/> boost: ASIO: io_service IO; <br/> boost: ASIO: deadline_timer T (Io, boost: posix_time: seconds (5); <br/> T. async_wait (print); <br/> Io. run (); <br/> return 0; <br/>}< br/>
It is also very simple to use. However, asynchronous timers also increase complexity, such as the validity of the object's life cycle. In this case, you can use them with smart pointers.

Details and precautions:

1. Implementation Details of the timer queue

There is a timer_queue member in io_service to manage timer, but it is not a queue in the traditional sense. Timer has two indexes in the queue. One is the multi hashmap with the timer address as the index (which can be understood in this way by concept, implements hashmap + linked list), and the other is the heap, the trigger time is sorted from small to large, and the timer callback with the trigger time <current time is executed for each dispatch. According to the heap nature, the complexity of adding the timer to the heap is O (log n), but it is not that bad in most cases (for details, see Wikipedia)

If we have a heap, and we add an element, we can perform an operation known as up-heap, bubble-up, percolate-up, sift-up, or heapify-up in order to restore the heap property. we can do this in O (log n) time. (Omitted) However, since approximately 50% of the elements are leaves and 75% are in the bottom two levels, it is likely that the new element to be inserted will only move a few levels upwards to maintain the heap. thus, binary heaps support insertion in average constant time, O (1 ).

Timer's data records the index in the heap, and deletion is also the time complexity of O (log n) (used to adjust the heap ).

If a large number of timer high-frequency insertion and deletion requirements exist, performance may be affected. If this happens, you can customize the timer management mechanism at the upper layer of io_service. But do not optimize it too early.

2. Timer Life Cycle

Adding timer to io_service is not actually adding the timer object, but handler and time information. Timer_queue encapsulates the data internally and uses the timer address as the index, but does not access the memory it refers. Therefore, if the timer object is deleted before the timer is triggered, the callback will also be called as usual. Possible problems are: if the memory of the timer is recycled, the memory is allocated to new_timer, and new_timer is added to io_service (). At this time, io_service () is called () when new_timer is removed, the timer callback is also removed. If you need to strictly ensure that this situation does not happen, you need to control the life cycle of timer.

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.