Run some code in a thread.

@param callable $func The function to execute
@param array|mixed $args The arguments (or a single argument) to pass to the function

@return int The pid of the thread created to execute this code
481287
public function call(callable $func, $args = null)
    {
        $pid = pcntl_fork();

        if ($pid == -1) {
            throw new \Exception("Failed to fork");
        }

        # If this is the child process, then run the requested function
        if (!$pid) {
            try {
                if ($args === null) {
                    $func();
                } else {
                    call_user_func_array($func, $args);
                }
            } catch(\Exception $e) {
                $memory = shmop_open($this->memoryKey, "c", 0644, static::SHARED_MEMORY_LIMIT);
                $errors = shmop_read($memory, 0, static::SHARED_MEMORY_LIMIT);
                $errors = trim($errors);
                if ($errors) {
                    $errors .= "\n";
                }
                $errors .= "Exception: " . $e->getMessage() . " (" . $e->getFile() . ":" . $e->getLine() . ")";
                shmop_write($memory, $errors, 0);
                shmop_close($memory);
                exit(1);
            }

            # Then we must exit or else we will end up the child process running the parent processes code
            die();
        }

        $this->threads[$pid] = $pid;

        return $pid;
    }
550399
public function run(array $args = [], callable $final = null, callable $fail = null)
    {
        $result = null;

        // declare default final middleware
        if (!is_callable($final)) {
            $final = function ($command) {
                return $command;
            };
        }

        // declare default error middleware
        if (!is_callable($fail)) {
            $fail = function ($exception) {
                throw $exception;
            };
        }

        try {
            $result = $this->handle($args, $final);
        } catch (\Exception $exception) {
            $result = $this->handleError($args, $fail, $exception, $result);
        }

        return $result;
    }
712202
function relay($funcs,$args=NULL) {
		foreach (is_array($funcs)?$funcs:$this->split($funcs) as $func)
			$args=[$this->call($func,$args)];
		return array_shift($args);
	}
1088827
protected static function runFunc($obj, string $func, array $args = []) {
		$reflectionClass = new ReflectionClass($obj);
		$method          = $reflectionClass->getMethod($func);
		$closure         = $method->getClosure($obj);
		return $closure(...$args);
	}
267058
public function callback($func) {
        if (!$this->_isValid) {
            return $this;
        }
        $this->_isValid = (bool) $func($this->_unsafeVar);
        return $this;
    }
1310598
def run(self, *args, **kwargs) -> Callable:
        
        return self.fn(*args, **kwargs) if args or kwargs else self.fn
875505
public function transactional(callable $func)
    {
        if (!\is_callable($func)) {
            throw new \InvalidArgumentException('Expected argument of type "callable", got "' . \gettype($func) . '"');
        }

        $this->connect();
        $this->pdo->beginTransaction();

        try {
            $return = $func($this);
            $this->pdo->commit();

            return $return ?: true;
        } catch (\Throwable $e) {
            $this->pdo->rollBack();
            throw $e;
        }
    }
1090993
public function allowPhpFunction($func)
	{
		if (is_array($func))
			foreach ($func as $fname)
				$this->allowedPhpFunctions[strtolower($fname)] = true;
		else
			$this->allowedPhpFunctions[strtolower($func)] = true;
	}
91185
public static void run(StreamFunctionExecutor functionExecutor, String... args) {
        parseData(args, (data, isDebug) -> {
            try (InputStream input = data != null ? new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)) : System.in) {
                functionExecutor.execute(input, System.out);
            } catch (Exception e) {
                exitWithError(isDebug, e);
            }
        });
    }
629815
function until($func,$args=NULL,$timeout=60) {
		if (!$args)
			$args=array();
		$time=time();
		$limit=max(0,min($timeout,$max=ini_get('max_execution_time')-1));
		$out='';
		$flag=FALSE;
		// Not for the weak of heart
		while (
			// Still alive?
			!connection_aborted() &&
			// Got time left?
			(time()-$time+1<$limit) &&
			// Restart session
			$flag=@session_start() &&
			// CAUTION: Callback will kill host if it never becomes truthy!
			!($out=$this->call($func,$args))) {
			session_commit();
			ob_flush();
			flush();
			// Hush down
			sleep(1);
		}
		if ($flag) {
			session_commit();
			ob_flush();
			flush();
		}
		return $out;
	}
1142906
public static function run($args=null){
      if (PHP_SAPI != 'cli') return false;
      if($args) {
        $_args = $args;
        static::$file = basename(isset($_SERVER['PHP_SELF'])?$_SERVER['PHP_SELF']:__FILE__);
       } else {
        $_args = $_SERVER['argv'];
        static::$file = basename(array_shift($_args));
      }
      foreach($_args as $e) if(strpos($e,'-')===0) {
        $h = explode('=',$e);
        static::$options[ltrim(current($h),'-')] = isset($h[1])?$h[1]:true;
      } else {
        static::$arguments[] = $e;
      }

      if(isset(static::$arguments[0])){
        $command = array_shift(static::$arguments);
        if (empty(static::$commands[$command]))
          return static::triggerError("Unknown command [".$command."].");
        $cmd = static::$commands[$command];
        $pars_vector = [];
        foreach ($cmd[0] as $_idx => $segment) {
          if ($segment[0]==':'){
            // Extract paramenter
            if (isset(static::$arguments[$_idx])){
               $pars_vector[] = static::$arguments[$_idx];
            } else return static::triggerError("Command [".$command."] needs more parameters");
          } else {
            // Match command
            if (empty(static::$arguments[$_idx]) || $segment!=static::$arguments[$_idx])
              return static::triggerError("Command [".$command."] is incomplete.");
          }
        }
        $returns = call_user_func_array($cmd[1], $pars_vector);
        echo is_scalar($returns) ? "$returns" : json_encode($returns, JSON_PRETTY_PRINT);
        return true;
      } else {
        static::help();
        return false;
      }
    }
1112762
protected function call($method, $args)
    {
        $method = str_replace("_", ".", $method);
        $request = new $this->requestClass($this->apiKey, $method, $args, $this->secure);
        return $request->execute();
    }
109389
function grab($func,$args=NULL) {
		if (preg_match('/(.+)\h*(->|::)\h*(.+)/s',$func,$parts)) {
			// Convert string to executable PHP callback
			if (!class_exists($parts[1]))
				user_error(sprintf(self::E_Class,$parts[1]),E_USER_ERROR);
			if ($parts[2]=='->') {
				if (is_subclass_of($parts[1],'Prefab'))
					$parts[1]=call_user_func($parts[1].'::instance');
				else {
					$ref=new ReflectionClass($parts[1]);
					$parts[1]=method_exists($parts[1],'__construct')?
						$ref->newinstanceargs($args):
						$ref->newinstance();
				}
			}
			$func=array($parts[1],$parts[3]);
		}
		return $func;
	}
695458
private function runAction($action, $args)
    {
        $function = $action['function'];
        $argsNumber = $action['arguments'];

        $class = (isset($function[0])) ? $function[0] : false;
        $method = (isset($function[1])) ? $function[1] : false;

        $args = $this->getArguments($argsNumber, $args);

        if (! ($class && $method) && function_exists($function)) {
            return call_user_func($function, $args);
        } elseif ($obj = call_user_func([$class, $this->singleton])) {
            if ($obj !== false) {
                return call_user_func_array([$obj, $method], $args);
            }
        } elseif (class_exists($class)) {
            $instance = new $class;

            return call_user_func_array([$instance, $method], $args);
        }
    }
133289
def run(self, func, *func_args, **func__kwargs):
        
        self._func = func
        self._func_args = func_args
        self._func_kwargs = func__kwargs
        return self
1281659
public function run(...$args): bool
    {
        $this->channel = new Channel($this->messageBuffer);

        $this->pid = pcntl_fork();

        // If $pid is set, we are in the parent process
        if ($this->pid) {
            // If we want the process to run asynchronously,
            // we can just store the PID and abandon it
            if ($this->async) {
                // Store the communication channel for the process
                $this->asyncChannels[$this->pid] = $this->channel;

                return true;
            }

            // Wait for the child process to complete before continuing
            return $this->wait();
        }

        // If $pid is not set, we are in the child process
        if (!$this->pid) {
            // Bind the channel as the $this argument within the handler
            $handler = $this->handler;
            $handler = $handler->bindTo($this->channel);

            // Call the handler
            $successful = $handler(...$args);

            // Capture the return value from the function and use
            // it to set the exit status for the process
            $status = $successful ? 0 : 1;

            // Exit the child process
            exit($status);
        }

        // We shouldn't ever get this far, so if we do
        // something went wrong
        return false;
    }
1367621
private function call($method, array $args)
    {
        $request = $this->rpcProtocol->encodeRequest($method, $args);

        $response = $this->transport->request($request);

        $response = $this->rpcProtocol->decodeValue($response);

        if ($response instanceof \Exception) {
            throw $response;
        }

        return $response;
    }