【php学习笔记】ticks篇

1. 什么是ticks


我们来看一下手冊上面对ticks的解释:

A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare block's directive section.


总结一下:

  • tick是一个事件
  • tick事件在每运行N条low-level statements就会放生一次,N由declare语句指定
  • 能够用register_tick_function()来指定时间的handler,unregister_tick_function()与之相应

至于什么是low-level statements。在此不做展开,总结来说,low-level statements包含下面几种情况:

(1)简单语句:空语句(一个。号)。return, break, continue, throw, goto, global, static, unset, echo, 内置的HTML文本。分号结束的表达式等均算一个语句。
(2)复合语句:完整的if、elseif, while, do...while, for, foreach, switch, try...catch等算一个语句
(3)语句块:{}大括号算一个语句块
(4)declare本身算一个复合语句

全部的statement, function_declare_statement, class_declare_statement构成了low-level statement.


2. tick的坑

一定要注意的一点是:declare()不是一个函数!!。准确的说,他是说一个语言结构。因此可能会有一些你意想不到的行为。比方说,当你在一个文件其中多次用到declare()时,其解析的原则是:谁在我前面而且理我近期我就用谁,全然无视你的代码逻辑。这里不做展开。一个建议的使用方法是

declare(ticks=10){
    for($i = 0; $i < 20; $i++){
        print "hello
";
    }
}

declare(ticks=2){
    for($i = 0; $i < 20; $i++){
        print "hello
";
    }
}

3. tick的应用

说了这么多,我们究竟什么时候会用到tick呢?一般来说,tick能够用作调试,性能測试,实现简单地多任务或者做后台的I/O操作等等。

这边举一个鸟哥提供的范例,用于完毕通信

<?php

/*
 * 利用ticks来完毕消息通信
 */

//create a message queue
$mesg_key = ftok(__FILE__, 'm');
$mesg_id = msg_get_queue($mesg_key, 0666);

//ticks callback
function fetchMessage($mesg_id) {
    if (!is_resource($mesg_id)) {
        print_r("Mesg Queue is not Ready 
");
    }

    if (msg_receive($mesg_id, 0, $mesg_type, 1024, $mesg, false, MSG_IPC_NOWAIT)) {
        print_r("Process got a new incoming MSG: $mesg 
");
    }
}

//register ticks callback
register_tick_function("fetchMessage", $mesg_id);

//send messages;
declare(ticks = 2) {
    $i = 0;
    while (++$i < 100) {
        if ($i % 5 == 0) {
            msg_send($mesg_id, 1, "Hi: Now Index is :" . $i);
        }
    }
}


我们来看一下输出:


我们发现,因为注冊了tick事件的callback,每经过两个statements都会触发tick事件。从而运行了从消息队列其中取消息的操作。这样就模拟了消息的发送和接收的过程。




原文地址:https://www.cnblogs.com/jhcelue/p/7019241.html