Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class SleepThread extends Thread
- {
- public $c = 0;
- public $hit = false;
- public function __construct($nap, $n)
- {
- $this->nap = $nap;
- $this->thread_no = $n;
- }
- public function run()
- {
- while (1)
- {
- $r = mt_rand(0, 9);
- echo $r . " found in thread " . $this->thread_no . "\n";
- if ($r == 9)
- {
- $this->hit = true;
- }
- if ($this->hit)
- {
- $this->synchronized
- (
- function ()
- {
- $obj = new stdClass;
- $obj->message = "Test\n";
- echo "CHILD: Hit... \n";
- $this->result = 'CHILD: DONE in thread ' . $this->thread_no . ' at ' . time();
- echo "CHILD: Waiting for parent thread ... \n";
- $time = microtime();
- $this->wait();
- echo "CHILD: Done waiting after " . (microtime() - $time) . " seconds\n";
- $this->hit = false;
- echo "CHILD: Child thread continuing. Thread number is: " . $this->thread_no . " You're a thread master.\n";
- }
- );
- }
- sleep($this->nap);
- }
- }
- }
- $thread[0] = new SleepThread(5, "0");
- $thread[1] = new SleepThread(5, "1");
- foreach ($thread as $job)
- {
- $job->start();
- }
- while (1)
- {
- sleep(1);
- foreach ($thread as $job)
- {
- if ($job->hit)
- {
- echo ("PARENT: Detected a hit in thread " . $job->thread_no . "\n");
- $job->synchronized
- (
- function ($job)
- {
- echo "PARENT: Notifying child thread that we are ready for its result.\n";
- $job->notify();
- echo "PARENT: " . $job->result . " <----That's the result.\n";
- // echo "PARENT: " . $job->obj->message . "^^^Getting object created in child thread oesn't work for some rasons^^^.\n";
- },
- $job
- );
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement