refrence
https://leetcode-cn.com/problems/print-in-order/solution/an-xu-da-yin-by-leetcode/
準(zhǔn)備工具:
1.Threading Lock
就是一把鎖,acquire調(diào)用睬捶,如果沒有資源進(jìn)入等待
release釋放屈藐。
1.Threading Thread
然后用Thread來創(chuàng)建進(jìn)程,start()跑進(jìn)程
多線程的創(chuàng)建可以用for循環(huán)鱼填,也可以
class Foo:
def __init__(self):
self.firstJobDone = Lock()
self.secondJobDone = Lock()
self.ThirdJobDone = Lock()
self.firstJobDone.acquire()
self.secondJobDone.acquire()
# self.ThirdJobDone.acquire()
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first".
self.ThirdJobDone.acquire()
printFirst()
# Notify the thread that is waiting for the first job to be done.
self.firstJobDone.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
# Wait for the first job to be done
self.firstJobDone.acquire()
# printSecond() outputs "second".
printSecond()
# Notify the thread that is waiting for the second job to be done.
self.secondJobDone.release()
def third(self, printThird: 'Callable[[], None]') -> None:
# Wait for the second job to be done.
self.secondJobDone.acquire()
# printThird() outputs "third".
printThird()
self.ThirdJobDone.release()
def printFirst():
print("one", end="")
def printSecond():
print("two", end="")
def printThird():
print("three", end="")
if __name__ == '__main__':
obj = Foo()
for i in range(500):
Thread(target=obj.second, args=(printSecond,)).start()
Thread(target=obj.third, args=(printThird,)).start()
Thread(target=obj.first, args=(printFirst,)).start()
Linux 編程
python -c ‘’
抱歉药有,我只會(huì)這個(gè)
ps 多進(jìn)程,一個(gè)坑苹丸,以后補(bǔ)上愤惰。
# https://blog.csdn.net/iterate7/article/details/102883956
from multiprocessing import Pool, Process, managers
def f(x):
return x*x
data = [1,2,3,4,5,6,9,7,8]
def task_multiprocessing():
with Pool(4) as p:
ret = p.map(f, data)
print(ret)
import requests
from concurrent.futures import ThreadPoolExecutor
urls = [
'http://www.python.org',
'https://docs.python.org/3/',
'https://docs.python.org/3/whatsnew/3.7.html',
'https://docs.python.org/3/tutorial/index.html',
'https://docs.python.org/3/library/index.html',
'https://docs.python.org/3/reference/index.html',
'https://docs.python.org/3/using/index.html',
'https://docs.python.org/3/howto/index.html',
'https://docs.python.org/3/installing/index.html',
'https://docs.python.org/3/distributing/index.html',
'https://docs.python.org/3/extending/index.html',
'https://docs.python.org/3/c-api/index.html',
'https://docs.python.org/3/faq/index.html'
]
def task_multithread():
with ThreadPoolExecutor(4) as executor:
results = executor.map(requests.request, 'GET', urls)
for i in results:
print(i)
print()
if __name__ == '__main__':
task_multiprocessing()
task_multithread()
import sys
print(sys.path)
func = task_multithread
print(func.__class__)
nums = [12,2,34]