PHP如何利用sleep实现 输出->等待->输出

sleep()函数一般用在暂停上,但是一个PHP一旦有了sleep,其他的输出(print,echo)就都要等待sleep()函数的完成,这是因为缓冲区,这里有详细解释

在这里不赘述,而如果要实现先输出再等待再输出,则用到了ob_flush()和flush();

上面链接的文章有这样一段,解释了为什么需要ob_flush()和flush();

在没有开启缓存时,脚本输出的内容都在服务器端处于等待输出的状态 ,flush()可以将等待输出的内容立即发送到客户端。

开启缓存后,脚本输出的内容存入了输出缓存中 ,这时没有处于等待输出状态的内容,你直接使用flush()不会向客户端发出任何内容。而 ob_flush()的作用就是将本来存在输出缓存中的内容取出来,设置为等待输出状态,但不会直接发送到客户端 ,这时你就需要先使用 ob_flush()再使用flush(),客户端才能立即获得脚本的输出。

 

所以代码是这样的

<?php

    echo date('h:i:s').'</br>';
    ob_flush();
    flush(); 
    sleep(5);
    echo date('h:i:s');
?>

 

转载于:https://www.cnblogs.com/wlgclining/p/8413554.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解决这个问题。你可以使用一个共享的队列来实现。其中一个线程作为生产者,负责往队列中添加数据,另一个线程作为消费者,负责从队列中取出数据并输出。 以下是一个简单的 Python 代码示例: ```python import threading import time queue = [] condition = threading.Condition() class ProducerThread(threading.Thread): def run(self): global queue nums = range(1, 5) global condition for num in nums: condition.acquire() queue.append(num) print("t1 --->", num) condition.notify() condition.release() time.sleep(1) class ConsumerThread(threading.Thread): def run(self): global queue global condition while True: condition.acquire() if not queue: print("t2 waiting") condition.wait() print("t2 notified") num = queue.pop(0) print("t2 --->", num) condition.release() time.sleep(1) producer = ProducerThread() consumer = ConsumerThread() producer.start() consumer.start() ``` 在这个示例中,我们定义了一个队列和一个条件变量 `condition`。生产者线程 `ProducerThread` 负责往队列中添加数据,并在添加完数据后使用 `notify()` 方法通知消费者线程 `ConsumerThread` 可以取出数据了。消费者线程则负责从队列中取出数据并输出。 使用 `acquire()` 和 `release()` 方法来加锁和解锁,保证线程安全。当队列为空时,消费者线程会调用 `wait()` 方法等待通知。 运行这个程序,你会得到以下输出: ``` t1 ---> 1 t2 waiting t1 ---> 2 t2 notified t2 ---> 1 t1 ---> 3 t2 waiting t1 ---> 4 t2 notified t2 ---> 2 t2 ---> 3 t2 ---> 4 ``` 可以看到,两个线程交替输出了所需的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值