如果之前有人问过这个问题,请原谅我。我环顾四周,但我觉得我没有合适的词汇来通过搜索网络找到它。
我在 python 中有一个多线程应用程序。我希望能够锁定某个代码块,但只能锁定具有特定条件的其他线程。让我举个例子:有三个线程,thread_a,thread_b和thread_c。每个线程都可以foo随时运行该函数。我不希望任何两个bar彼此相等的线程能够同时访问Code block ALPHA。但是,我不想阻止bar值不同的线程。在这种情况下,假设首先thread_a有一个bar == "cat"和命中线(3)。在thread_ahits line之前(5),让我们说thread_b, with bar == "cat"hits line (3)。我愿意thread_b等待。但如果thread_c出现,与bar == "dog",我希望它能够继续前进。
(1) def foo(bar):
(2)
(3) lock(bar)
(4) # Code block ALPHA (two threads with equivalent bar should not be in here)
(5) unlock(bar)
Run Code Online (Sandbox Code Playgroud)
另请注意, 的可能值bar是完全不可预测的,但发生碰撞的可能性非常高。
感谢您的任何帮助。我正在查看的库是python …
我目前正在尝试使用带有多处理后端的 joblib 库在 python 3.5 中运行并行进程。但是,每次运行时都会出现此错误:
Process ForkServerPoolWorker-5:
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap
self.run()
File "/opt/anaconda3/lib/python3.5/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/opt/anaconda3/lib/python3.5/multiprocessing/pool.py", line 108, in worker
task = get()
File "/opt/anaconda3/lib/python3.5/site-packages/joblib/pool.py", line 362, in get
return recv()
File "/opt/anaconda3/lib/python3.5/multiprocessing/connection.py", line 251, in recv
return ForkingPickler.loads(buf.getbuffer())
TypeError: __new__() missing 1 required positional argument: 'path'
Run Code Online (Sandbox Code Playgroud)
这是我用来运行它的 joblib 代码:
from joblib import Parallel, delayed
results = Parallel(n_jobs=6) (
delayed(func)(i) for i in array)
Run Code Online (Sandbox Code Playgroud)
默认情况下,后端是多处理的。当我将后端更改为“线程”时,代码运行良好,但对于我的用例,与使用多处理相比,线程效率低下。
我还尝试使用以下代码直接使用多处理,但我仍然遇到相同的错误: …
python runtime-error python-multithreading joblib python-multiprocessing
我有以下已简化的代码:
import concurrent.futures
pool = concurrent.futures.ThreadPoolExecutor(8)
def _exec(x):
return x + x
myfuturelist = pool.map(_exec,[x for x in range(5)])
# How do I wait for my futures to finish?
for result in myfuturelist:
# Is this how it's done?
print(result)
#... stuff that should happen only after myfuturelist is
#completely resolved.
# Documentation says pool.map is asynchronous
Run Code Online (Sandbox Code Playgroud)
关于 ThreadPoolExecutor.map 的文档很薄弱。帮助会很棒。
谢谢!
我目前正在使用 pytest 来测试现有的(根据文档的unittest测试套件)。我目前正在编写一个线程,等待分配 IP 地址,然后将其返回给回调函数,并且我正在编写单元测试来配合它。
这是我编写的测试用例类。
class TestGetIpAddressOnNewThread(unittest.TestCase):
def test_get_existing_ip(self):
def func(ip):
assert ip == "192.168.0.1" # Not the real IP
# Even when I introduce an assert statement that should fail, test still passes
assert ip == "shouldn't be the ip"
ip_check = GetInstanceIpThread(instance, func)
ip_check.start()
ip_check.join()
if __name__ == '__main__':
pytest.main()
Run Code Online (Sandbox Code Playgroud)
这是GetInstanceIpThread伪定义:
class GetInstanceIpThread(threading.Thread):
def __init__(self, instance, callback):
threading.Thread.__init__(self)
self.event = threading.Event()
self.instance = instance
self.callback = callback
def run(self):
self.instance.wait_until_running()
ip = self.instance.ip_address
self.callback(ip) …Run Code Online (Sandbox Code Playgroud) 我有一个 Flask 应用程序,在命令行上运行时可以正常工作,但是当它通过 uWSGI 运行时,它无法正确响应请求或工作线程无法正常工作。我重写了一个简单的概念验证/失败程序来演示这个问题:
from datetime import datetime
from threading import Event, Thread
from flask import Flask
class JobManager:
def __init__(self):
self.running = False
self.event = Event()
def start(self):
self.running = True
while self.running:
print("Processing Job at", datetime.now().strftime('%c'))
self.event.clear()
self.event.wait(5)
if self.event.is_set():
print("Interrupted by request!")
def stop(self):
self.running = False
self.event.set()
app = Flask(__name__)
jobs = JobManager()
t = Thread(target=jobs.start)
t.start()
@app.route('/')
def hello_world():
global jobs
jobs.event.set()
return "I'm alive at " + datetime.now().strftime('%c')
if __name__ == '__main__':
app.run() …Run Code Online (Sandbox Code Playgroud) 据我了解,GIL使得不可能拥有分别利用内核的线程。
这是一个基本问题,但是threading库的意义是什么?如果线程代码的速度与普通程序相当,这似乎没有用。
python multithreading python-multithreading python-multiprocessing
我有一个关于 pytest 的问题
我想使用多个线程运行相同的 pytest 脚本。但是,我不确定如何创建和运行传递多个参数的线程。(并使用 pytest 运行线程..)
例如我有 test_web.py
from selenium import webdriver
import pytest
class SAMPLETEST:
self.browser = webdriver.Chrome()
self.browser.get(URL)
self.browser.maximize_window()
def test_title(self):
assert "Project WEB" in self.browser.title
def test_login(self):
print('Testing Login')
ID_BOX = self.broswer.find_element_by_id("ProjectemployeeId")
PW_BOX = self.broswer.find_element_by_id("projectpassword")
ID_BOX.send_keys(self.ID) # this place for ID. This param come from thread_run.py
PW_BOX.send_keys(self.PW) # this place for PW. It is not working. I am not sure how to get this data from threa_run.py
PW_BOX.submit()
Run Code Online (Sandbox Code Playgroud)
在 thread_run.py
import threading
import time
from …Run Code Online (Sandbox Code Playgroud) selenium multithreading pytest python-multithreading python-3.x
我正在研究并试图了解 python GIL 和在 python 中使用多线程的最佳实践。我找到了这个演示文稿和这个视频
我试图重现演示文稿前 4 张幻灯片中提到的奇怪和疯狂的问题。这个问题老师在视频中也提到过(前4分钟)。我写了这个简单的代码来重现问题
from threading import Thread
from time import time
BIG_NUMBER = 100000
count = BIG_NUMBER
def countdown(n):
global count
for i in range(n):
count -= 1
start = time()
countdown(count)
end = time()
print('Without Threading: Final count = {final_n}, Execution Time = {exec_time}'.format(final_n=count, exec_time=end - start))
count = BIG_NUMBER
a = Thread(target=countdown, args=(BIG_NUMBER//2,))
b = Thread(target=countdown, args=(BIG_NUMBER//2,))
start = time()
a.start()
b.start()
a.join()
b.join()
end = time()
print('With Threading: …Run Code Online (Sandbox Code Playgroud) 我的脚本遍历输入文件的每一行,并使用每一行中的字符串执行一些操作。由于在每一行上执行的任务是相互独立的,我决定将任务分开,threads这样脚本就不必等待任务完成才能继续循环。代码如下。
def myFunction(line, param):
# Doing something with line and param
# Sends multiple HTTP requests and parse the response and produce outputs
# Returns nothing
param = arg[1]
with open(targets, "r") as listfile:
for line in listfile:
print("Starting a thread for: ",line)
t=threading.Thread(target=myFunction, args=(line, param,))
threads.append(t)
t.start()
Run Code Online (Sandbox Code Playgroud)
我意识到这是一个坏主意,因为输入文件中的行数越来越大。使用此代码,线程数将与行数一样多。研究了一下,认为这queues就是方法。
我想了解在这种情况下使用队列的最佳方式,以及是否有任何我可以使用的替代方案。
我需要在 Mac 和 Windows 上为 python 3 提供定时输入,如果用户没有时间,它会自动选择其中一个选项。我见过的问题的所有其他答案只有在用户按“Enter”键后才会终止。无论是否按下“Enter”键,我都需要它终止。
例如,在我的国际象棋程序中,如果5秒后没有输入,我需要它自动选择“Q”。另外,如果输入不在 [“Q”,“R”,“B”,“N”] 中,那么我还需要它来选择“Q”。
下面的代码不起作用。它会要求输入然后永远等待;计时器根本不工作。
def countdown():
global timer
timer = 5
for x in range(timer):
timer -= 1
time.sleep(1)
countdownThread = threading.Thread(target=countdown)
countdownThread.start()
while timer > 0:
promotedPiece = input("Promote to Q, R, B or N? > ").upper()
if timer == 0:
break
if timer == 0:
if promotedPiece not in ["Q", "R", "B", "N"]: # If not valid input, choose Queen
promotedPiece = "Q"
print("Queen auto selected")
Run Code Online (Sandbox Code Playgroud) python multithreading timer python-multithreading python-3.x