早睡早起,方能养生
Sleep early rise early, way to keep healthy

PHP多线程使用线程池

super
2023-11-10 16:38
views 1223

如果没有安装多线程拓展,请看

 

https://rongsp.com/article/371.html

 

<?php

function curl_post($url, $post_data)
{
    $header = [
        'Accept: application/json',
    ];

    // 初始化
    $curl = curl_init();
    // 设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    // 设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, false);
    // 设置获取的信息以文件流的形式返回,而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // 超时设置
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);

    // 超时设置,以毫秒为单位
    // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

    // 设置请求头
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE );

    // 设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    // 执行命令
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);

    // 显示错误信息
    if ($error) {
        // print "Error: " . $error;
        return ['code' => 500, 'msg' => $error];
    } else {
        // 打印返回的内容
        // var_dump($data);
        // print_r(json_decode($data, true));
        return ['code' => 200, 'msg' => '', 'data' => $data];
    }
}

class Login extends Thread
{
    private $account;
    private $password;
    public $res;

    public function __construct($account, $password) {
        $this->account = $account;
        $this->password = $password;
    }

    public function run() {
        $res = curl_post('http://xxxx.net/login.php', ['account' => $this->account, 'password' => $this->password]);
        print_r($res);
    }
}

$pool = new Pool(100);

for($i = 1; $i <= 100; $i++) {
    $pool->submit(new Login($i, $i));
}

$pool->shutdown();


分享
0 条讨论
top