python 简单多线程

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@author: carry
@file: api.py
@time: 2019/10/8 11:37
@desc:
'''
import requests
import json
import base64
import threading
import time

path = './media/test_images/14002455_20190801172429370_chunji.jpg'


def get_api():
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read()).decode()
    import uuid
    uuid = str(uuid.uuid4()).replace('-', '')

    api_params = json.dumps({'uuid': uuid, 'image': img_byte})
    res = requests.post('http://127.0.0.1:8885/app/pcmp/', data=api_params)
    print(res.text)


class MyThread(threading.Thread):
    def run(self):
        print(self.name)
        get_api()


def test():
    for i in range(10):
        t = MyThread()
        t.start()


if __name__ == '__main__':
    for i in range(10):
        get_api()
    # test()

threading提供了如下方法: 
- run(): 用以表示线程活动的方法。 
- start():启动线程活动。 
- join([time]): 等待至线程中止。 
- isAlive(): 返回线程是否活动的。 
- getName(): 返回线程名。 
- setName(): 设置线程名。

带参数 带返回值的多线程

import threading
import time

"""重新定义带返回值的线程类"""


class MyThread(threading.Thread):
    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        print(self.name, self.args)
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result
        except Exception:
            return None


"""测试函数,计算两个数之和"""


def fun(a, s):
    print('我是参数:', a)
    return '结果'


li = []
for i in range(4):
    t = MyThread(fun, args=(i, i + 1))
    li.append(t)
    t.start()
for t in li:
    t.join()  # 一定要join,不然主线程比子线程跑的快,会拿不到结果
    print(t.get_result())

multiprocessing

import multiprocessing as mul  进程

import multiprocessing.dummy as mul (线程)


def f(x):
    return x ** 2


if __name__ == '__main__':
    pool = mul.Pool(5)
    rel = pool.map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    print(rel)

多个参数

def work(item):
    (x, y) = item
    return x + y


x_y = [(1, 1), (2, 2), (3, 3)]
results = pool.map(work, x_y)

传参带返回的

import multiprocessing


def worker(name, q):
    t = (name, name ** 2)
    q.put(t)


q = multiprocessing.Queue()
jobs = []
for i in range(10):
    p = multiprocessing.Process(target=worker, args=(i, q))
    jobs.append(p)
    p.start()

for p in jobs:
    p.join()

results = [q.get() for j in jobs]
print(results)

RAY

# 导入ray,并初始化执行环境
import ray
import time

ray.init()


# 定义ray remote函数
@ray.remote
def hello(n):
    print('sleep')
    time.sleep(2)
    return "Hello world ! " + n


li = []
for s in ['1', '2', '3', '4', '5', '6']:
    object_id = hello.remote(s)
    li.append(object_id)
for i in li:
    ret = ray.get(i)
    print(ret)


异步多线程

from concurrent.futures import ThreadPoolExecutor,wait

https://www.jianshu.com/p/b9b3d66aa0be

猜你喜欢

转载自blog.csdn.net/xkx_07_10/article/details/102724187