Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter from main thread to new thread

How can I pass a parameter from my main thread to a new thread in PHP using the extension pthreads?

Something similar to this How can I pass a parameter to a Java Thread? just in PHP.

like image 580
Junior Avatar asked Jun 13 '14 17:06

Junior


People also ask

Can we pass parameter in thread?

The first way we can send a parameter to a thread is simply providing it to our Runnable or Callable in their constructor.

How do you pass data between two threads in Java?

If you want synchronous communication between a main thread and a processing thread, you can use a SynchronousQueue. The idea is that the main thread passes data to the processing thread by calling put() , and the processing thread calls take() .

How do you pass a parameter to a thread in C++?

In c++11 to pass a referenceto a thread, we have std::ref(). std::thread t3(fun3, std::ref(x)); In this statement we are passing reference of x to thread t3 because fun3() takes int reference as a parameter.

How can you ensure all threads that started from Main?

We can use join() methodto ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die. Calling join() method internally calls join(0);


2 Answers

Starting from this code:

http://www.php.net/manual/en/thread.start.php

<?php
class My extends Thread {
    public $data = "";
    public function run() {
        /** ... **/
    }
}
$my = new My();
$my->data = "something"; // Pass something to the Thread before you actually start it.
var_dump($my->start());
?>
like image 57
Promi Avatar answered Sep 22 '22 20:09

Promi


Just as you do with any other object in PHP [or any lanugage], you should pass parameters to constructors to set members.

class My extends Thread {

    public function __construct($greet) {
        $this->greet = $greet;
    }

    public function run() {
        printf(
            "Hello %s\n", $this->greet);
    }
}

$my = new My("World");
$my->start();
$my->join();

No special action need be taken for scalars and simple data that you are just passing around, however should you intend to manipulate an object in multiple threads, the object's class should descend from pthreads:

class Greeting extends Threaded {

    public function __construct($greet) {
        $this->greet = $greet;
    }

    public function fetch() {
        return $this->greet;
    }

    protected $greet;
}

class My extends Thread {

    public function __construct(Greeting $greet) {
        $this->greet = $greet;
    }

    public function run() {
        printf(
            "Hello %s\n", $this->greet->fetch());
    }
}

$greeting = new Greeting("World");
$my = new My($greeting);
$my->start();
$my->join();
like image 44
Joe Watkins Avatar answered Sep 24 '22 20:09

Joe Watkins