Advertisement
  1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[INFO] Using arrays while multithreading

Comments in 'Plugin Development' started by Falk, May 3, 2014.

  1. Falk
    Offline

    Falk Staff Member Global Moderator

    Joined:
    Sep 2, 2013
    Posts:
    1,707
    Plugins:
    22
    Minecraft User:
    Falkirknh
    As you may know, pthreads will not work well with arrays as it can't store them properly and it tries to serialize them. I spent a while trying to figure out how to get a basic array working.

    The below code just waits for messages and adds them to an ArrayObject which extends Stackable so it won't be serialized, so when you enter a message your console should be spammed repeatedly :)

    PHP:
    <?php
    /*
    __PocketMine Plugin__
    name=threadExample
    description=An Example!
    version=0.1
    author=Falk
    class=threadExample
    apiversion=11,12,13
    */
    class threadExample implements Plugin {
      private 
    $api;
      public function 
    __construct(ServerAPI $api$server false){
        
    $this->api $api;
      }
      public function 
    init(){
        
    $this->msg = new Messages();
        
    $this->loop = new msgLoop($this->msg);
        
    $this->loop->start();
        
    $this->api->addHandler("player.chat", array($this,"addMessage"),50);
      }
      public function 
    addMessage($data){
        
    $this->msg[] = $data['message'];
        
    var_dump($this->msg);
      }
      public function 
    __destruct(){
        
    $this->loop->stop();
      }
    }
    class 
    Messages extends Stackable{
       public function 
    __construct() {}
      public function 
    run(){}
    }
    class 
    msgLoop extends Thread {
      public 
    $t;
      public 
    $msg;
      public function 
    __construct(Messages $msg) {
        
    $this->= array();
        
    $this->stop false;
        
    $this->msg $msg;
      }
      public function 
    stop() {
        
    $this->stop true;
      }
      public function 
    run() {
        while (
    $this->stop === false) {
            if(
    count($this->msg)) var_dump($this->msg);
        }
        exit(
    0);
      }
    }
    Kedyn Bolds likes this.
  2. Humerus
    Offline

    Humerus Staff Member Plugin Reviewer

    Joined:
    Aug 23, 2013
    Posts:
    114
    Plugins:
    1

Share This Page

Advertisement