进程的概念起源于操作系统,是操作系统最核心的概念。
from os import getpid
from multiprocessing import Process
import requests
def parse_page(res):
print(getpid(), "正在解析", res.url, len(res.text))
def get_page(_url, callback=parse_page):
print(getpid(), "GET", _url)
response = requests.get(_url)
if response.status_code == 200:
callback(response)
urls = [
"https://www.baidu.com",
"https://www.cnblogs.com",
"https://www.python.org",
"https://www.github.com"
]
if __name__ == '__main__':
for url in urls:
p = Process(target=get_page, args=(url, ))
p.start()
from threading import Thread, get_ident
import requests
def parse_page(res):
print(get_ident(), "正在解析", res.url, len(res.text))
def get_page(_url, callback=parse_page):
print(get_ident(), "GET", _url)
response = requests.get(_url)
if response.status_code == 200:
callback(response)
urls = [
"https://www.baidu.com",
"https://www.cnblogs.com",
"https://www.python.org",
"https://www.github.com"
]
for url in urls:
t = Thread(target=get_page, args=(url,))
t.start()
from gevent import monkey;monkey.patch_all()
from gevent.threading import get_ident
import gevent
import requests
def parse_page(res):
print(get_ident(), "正在解析", res.url, len(res.text))
def get_page(_url, callback=parse_page):
print(get_ident(), "GET", _url)
response = requests.get(_url)
if response.status_code == 200:
callback(response)
urls = [
"https://www.baidu.com",
"https://www.cnblogs.com",
"https://www.python.org",
"https://www.github.com"
]
g_list = []
for url in urls:
g = gevent.spawn(get_page, url)
g_list.append(g)
gevent.joinall(g_list)
当一个进程/线程拿到数据使用权后,上一把锁,其余进程/线程看到数据被加锁就进入阻塞状态,直到锁被释放。
from multiprocessing import Process
import os,time
def work():
print('%s is running' %os.getpid())
time.sleep(2)
print('%s is done' %os.getpid())
if __name__ == '__main__':
for i in range(3):
p=Process(target=work)
p.start()
互斥锁简单实现
from threading import Thread, Lock, get_ident
import time
lock = Lock()
def task():
lock.acquire()
print(get_ident(), "开始执行任务")
time.sleep(2)
print(get_ident(), "结束任务")
lock.release()
for _ in range(5):
t = Thread(target=task)
t.start()
from threading import Thread, Lock, get_ident
import time
A = Lock()
def task():
print(get_ident(), "正在等待A资源")
A.acquire()
print(get_ident(), "拿到A资源")
print(get_ident(), "第二次等待A资源")
A.acquire()
print(get_ident(), "第二次拿到A资源")
time.sleep(1)
A.release()
print(get_ident(), "A资源使用完毕")
A.release()
print(get_ident(), "第二次A资源使用完毕")
for _ in range(1):
t = Thread(target=task)
t.start()
from threading import Thread, Lock, get_ident
import time
A = Lock()
B = Lock()
def task():
print(get_ident(), "正在等待A资源")
A.acquire()
print(get_ident(), "拿到A资源")
print(get_ident(), "正在等待B资源")
B.acquire()
print(get_ident(), "拿到B资源")
time.sleep(1)
A.release()
print(get_ident(), "A资源使用完毕")
time.sleep(1)
print(get_ident(), "第二次等待A资源")
A.acquire()
print(get_ident(), "第二次拿到A资源")
time.sleep(1)
A.release()
print(get_ident(), "A资源使用完毕")
B.release()
print(get_ident(), "B资源使用完毕")
for _ in range(3):
t = Thread(target=task)
t.start()