Vic*_*isi 14 python multithreading semaphore python-multithreading
几个星期前我开始用Python编程,并试图使用Semaphores同步两个简单的线程,用于学习目的.这是我得到的:
import threading
sem = threading.Semaphore()
def fun1():
while True:
sem.acquire()
print(1)
sem.release()
def fun2():
while True:
sem.acquire()
print(2)
sem.release()
t = threading.Thread(target = fun1)
t.start()
t2 = threading.Thread(target = fun2)
t2.start()
Run Code Online (Sandbox Code Playgroud)
但它一直打印只有1.如何对照片进行内部缩放?
Ben*_*ari 13
此外,您可以使用Lock/mutex方法如下:
import threading
import time
mutex = threading.Lock() # is equal to threading.Semaphore(1)
def fun1():
while True:
mutex.acquire()
print(1)
mutex.release()
time.sleep(.5)
def fun2():
while True:
mutex.acquire()
print(2)
mutex.release()
time.sleep(.5)
t1 = threading.Thread(target=fun1).start()
t2 = threading.Thread(target=fun2).start()
Run Code Online (Sandbox Code Playgroud)
使用“ with”的更简单的样式:
import threading
import time
mutex = threading.Lock() # is equal to threading.Semaphore(1)
def fun1():
while True:
with mutex:
print(1)
time.sleep(.5)
def fun2():
while True:
with mutex:
print(2)
time.sleep(.5)
t1 = threading.Thread(target=fun1).start()
t2 = threading.Thread(target=fun2).start()
Run Code Online (Sandbox Code Playgroud)
[注意]:
Ana*_*mar 12
它工作正常,只是它的打印速度太快,你无法看到.尝试将time.sleep()两个函数(少量)放入线程中休眠那段时间,实际上能够同时看到1和2.
示例 -
import threading
import time
sem = threading.Semaphore()
def fun1():
while True:
sem.acquire()
print(1)
sem.release()
time.sleep(0.25)
def fun2():
while True:
sem.acquire()
print(2)
sem.release()
time.sleep(0.25)
t = threading.Thread(target = fun1)
t.start()
t2 = threading.Thread(target = fun2)
t2.start()
Run Code Online (Sandbox Code Playgroud)
事实上,我想找到asyncio.Semaphores,而不是threading.Semaphore,而且我相信有人可能也想要它。
所以,我决定分享asyncio。Semaphores,希望你不要介意。
from asyncio import (
Task,
Semaphore,
)
import asyncio
from typing import List
async def shopping(sem: Semaphore):
while True:
async with sem:
print(shopping.__name__)
await asyncio.sleep(0.25) # Transfer control to the loop, and it will assign another job (is idle) to run.
async def coding(sem: Semaphore):
while True:
async with sem:
print(coding.__name__)
await asyncio.sleep(0.25)
async def main():
sem = Semaphore(value=1)
list_task: List[Task] = [asyncio.create_task(_coroutine(sem)) for _coroutine in (shopping, coding)]
"""
# Normally, we will wait until all the task has done, but that is impossible in your case.
for task in list_task:
await task
"""
await asyncio.sleep(2) # So, I let the main loop wait for 2 seconds, then close the program.
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
shopping
coding
shopping
coding
shopping
coding
shopping
coding
shopping
coding
shopping
coding
shopping
coding
shopping
coding
Run Code Online (Sandbox Code Playgroud)
16*0.25 = 2
| 归档时间: |
|
| 查看次数: |
26897 次 |
| 最近记录: |