我正在创建一个数据库连接,并在多个线程(大约 100 到 1000 个线程)之间共享它,我收到如下错误,
1)我的代码有什么问题?
这是我的示例代码,我将针对以下场景更改此代码: 基于一些 SQL 结果,它将创建最多 1000 个线程。 如果我为每个线程创建数据库连接,它将创建更多的数据库连接。为了避免这种情况,我在所有线程中使用了相同的数据库连接,我只有插入和更新操作。
2)这种多线程场景有没有更好的方法?
错误:
Worker: 0
Create Notification called for userid abcxyz and message is Test Message : Worker: 0 Attempt: 0
Sleeping ...
Worker: 1
Create Notification called for userid abcxyz and message is Test Message : Worker: 1 Attempt: 0
Partial insertedID 43
Traceback (most recent call last):
File "T:\work\Testing\src\notification_data_feeder.py", line 58, in createNotification
db.commit()
OperationalError: (2006, 'MySQL server has gone away')
Error on createNotification
Traceback (most …Run Code Online (Sandbox Code Playgroud) python multithreading mysql-python threadpool python-multithreading
我想使用 py.test 测试函数的线程安全性我的努力:
def function_to_be_tested(arg1,arg2):
some functionality
class Test:
def setup()
def teardown()
def test_conc()
p1=Process(taget=function_to_be_tested,args(arg1,arg2,))
p2=Process (taget=function_to_be_tested,args(arg1,arg3,))
p1.start()
p2.start()
p1.join()
p2.join()
Run Code Online (Sandbox Code Playgroud)
使用 py.test 命令执行上面的文件。这显示以下错误。
ExceptionPexpect: isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?
Run Code Online (Sandbox Code Playgroud)
你能帮我解码这个错误,并就如何做到这一点提供指导吗?
谢谢这是我正在尝试的实际代码和堆栈跟踪:
import pytest
from multiprocessing import Process
from pexpect import pxssh
def func(cls,b):
cls.s.sendline("bteq")
cls.s.prompt()
print b
#some operations inside the bteq session
class Test:
@classmethod
def setup_class(cls):
cls.s=pxssh.pxssh()
cls.s.login("IP",'Username','Pwd')
@classmethod
def …Run Code Online (Sandbox Code Playgroud) python concurrency pytest python-multithreading python-multiprocessing
基于这个优秀的 SO 答案,我可以在 RxPy 中并行处理多个任务,我的问题是你如何等待它们全部完成?我知道我可以使用线程,.join()但是 Rx 调度器似乎没有任何这样的选项。.to_blocking()也无济于事, MainThread 在触发所有通知并调用完整处理程序之前完成。下面是一个例子:
from __future__ import print_function
import os, sys
import time
import random
from rx import Observable
from rx.core import Scheduler
from threading import current_thread
def printthread(val):
print("{}, thread: {}".format(val, current_thread().name))
def intense_calculation(value):
printthread("calc {}".format(value))
time.sleep(random.randint(5, 20) * .1)
return value
if __name__ == "__main__":
Observable.range(1, 3) \
.select_many(lambda i: Observable.start(lambda: intense_calculation(i), scheduler=Scheduler.timeout)) \
.observe_on(Scheduler.event_loop) \
.subscribe(
on_next=lambda x: printthread("on_next: {}".format(x)),
on_completed=lambda: printthread("on_completed"),
on_error=lambda err: printthread("on_error: {}".format(err))) …Run Code Online (Sandbox Code Playgroud) 我似乎tkinter通过使用一些多线程来破坏linux。据我所知,我设法在不是主 GUI 线程的线程上触发垃圾回收。这导致__del__在一个tk.StringVar实例上运行,该实例试图tcl从错误的线程调用堆栈,从而导致 linux 上的混乱。
下面的代码是我能想出的最小例子。请注意,我没有用 做任何实际工作matplotlib,但否则我无法触发问题。在__del__对方法Widget验证的Widget情况下被从其他线程删除。典型的输出是:
Running off thread on 140653207140096
Being deleted... <__main__.Widget object .!widget2> 140653210118576
Thread is 140653207140096
... (omitted stack from from `matplotlib`
File "/nfs/see-fs-02_users/matmdpd/anaconda3/lib/python3.6/site-packages/matplotlib/text.py", line 218, in __init__
elif is_string_like(fontproperties):
File "/nfs/see-fs-02_users/matmdpd/anaconda3/lib/python3.6/site-packages/matplotlib/cbook.py", line 693, in is_string_like
obj + ''
File "tk_threading.py", line 27, in __del__
traceback.print_stack()
...
Exception ignored in: <bound method Variable.__del__ of <tkinter.StringVar object at 0x7fec60a02ac8>>
Traceback …Run Code Online (Sandbox Code Playgroud) 我正在玩 Python 的新(ish)asyncio东西,试图将其事件循环与传统线程结合起来。我编写了一个在自己的线程中运行事件循环的类,以隔离它,然后提供一个(同步)方法,该方法在该循环上运行协程并返回结果。(我意识到这使它成为一个有点毫无意义的例子,因为它必须序列化所有内容,但这只是一个概念验证)。
import asyncio
import aiohttp
from threading import Thread
class Fetcher(object):
def __init__(self):
self._loop = asyncio.new_event_loop()
# FIXME Do I need this? It works either way...
#asyncio.set_event_loop(self._loop)
self._session = aiohttp.ClientSession(loop=self._loop)
self._thread = Thread(target=self._loop.run_forever)
self._thread.start()
def __enter__(self):
return self
def __exit__(self, *e):
self._session.close()
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join()
self._loop.close()
def __call__(self, url:str) -> str:
# FIXME Can I not get a future from some method of the loop?
future = asyncio.run_coroutine_threadsafe(self._get_response(url), self._loop)
return future.result()
async def _get_response(self, url:str) -> str: …Run Code Online (Sandbox Code Playgroud) 我在一个环境中工作,Web 应用程序按需派生进程,每个进程都有自己的线程池来为 Web 请求提供服务。线程可能需要向外部服务发出 HTTPS 请求,目前使用 requests 库来执行此操作。当第一次添加 requests 用法时,通过为每个请求创建一个新的requests.Session和requests.adapters.HTTPAdapter甚至通过简单地调用requests.get或requests.post按需来使用它。出现的问题是每次都建立一个新连接,而不是潜在地利用 HTTP 持久连接。一个潜在的解决方法是使用连接池,但是在使用请求库时在线程之间共享 HTTP 连接池的推荐方法是什么?有吗?
第一个想法是共享一个requests.Session,但目前不安全,如“ Python 的请求库中的 Session 对象线程安全吗? ”和“ Session 类的文档线程契约”中所述。在每个线程中按需创建的 srequests.adapters.HTTPAdapter之间共享一个全局变量是否安全且足够requests.Sessions?根据“我们对 urllib3 的 ConnectionPools 的使用不是线程安全的。 ”,即使这样也可能不是有效的使用。无论如何,只需要连接到少量不同的远程端点就可以使它成为一种可行的方法。
python connection-pooling thread-safety python-multithreading python-requests
问题与标题一样,如何通过示例模拟 select.select 以测试我的线程运行功能。测试功能失败
ready = select.select([self.sock], [], [], 5)
TypeError: fileno() returned a non-integer
Run Code Online (Sandbox Code Playgroud)
和类型打印给出
输入'builtin_function_or_method'
所以很明显 select.select 在线程的范围内没有被模拟,而在测试中它是......(assert isinstance)
import select
import threading
RECEIVE_BYTES = 256
class Bar(threading.Thread):
def __init__(self, sock):
threading.Thread.__init__(self)
self.sock = sock
def run(self):
print type(select.select)
ready = select.select([self.sock],[],[],5)
if ready[0]:
print self.sock.recv(RECEIVE_BYTES)
Run Code Online (Sandbox Code Playgroud)
在另一个模块中测试如下
def test_run(self):
with patch("select.select"):
select.select.return_value = [True]
mock_sock = MagicMock()
foo = Bar(mock_sock)
assert isinstance(select.select, MagicMock)
foo.start()
Run Code Online (Sandbox Code Playgroud)
测试通过鼻子运行
python unit-testing mocking python-multithreading python-2.7
我有两个函数func1(),func2()它们相互独立,可以在两个线程中运行。我正在使用threading库python3来运行这两个线程。不过里面func1(),我也运行for使用并行循环joblib。因此,使用线程以及 joblib 会给出以下警告 -
/usr/local/lib/python3.6/dist-packages/joblib/parallel.py:547: UserWarning: Multiprocessing-backed parallel loops cannot be nested below threads, setting n_jobs=1,
然后里面的 for 循环func1()只是按顺序运行。
以下是代码片段的示例:
from joblib import Parallel, delayed
import threading
from math import sqrt
class MyThread(threading.Thread):
def __init__(self, sample, type):
threading.Thread.__init__(self)
self.type = type
self.sample = sample
def run(self):
if self.type=='func1':
self.sample.func1()
else:
self.sample.func2()
class Sample:
def func1(self):
print('this function runs for …Run Code Online (Sandbox Code Playgroud) 在看了比斯利书中的例子后,我正在和我的朋友交谈
class ActorExit(Exception):
pass
class Actor:
def __init__(self):
self._mailbox = Queue()
def send(self, msg):
self._mailbox.put(msg)
def recv(self):
msg = self._mailbox.get()
if msg is ActorExit:
raise ActorExit()
return msg
def close(self):
self.send(ActorExit)
def start(self):
self._terminated = Event()
t = Thread(target=self._bootstrap)
t.daemon = True
t.start()
def _bootstrap(self):
try:
self.run()
except ActorExit:
pass
finally:
self._terminated.set()
def join(self):
self._terminated.wait()
def run(self):
while True:
msg = self.recv()
class PrintActor(Actor):
def run(self):
while True:
msg = self.recv()
print('Got:', msg)
Run Code Online (Sandbox Code Playgroud)
我的朋友认为 Event 的唯一目的是阻塞主线程,直到另一个线程执行设置操作。真的吗?我们如何观察线程执行?
python queue concurrency multithreading python-multithreading
下面的脚本是抽象的。我的问题是关于使用threading.Lock()
锁定限制了对“共享资源”的访问,但我对这能走多远感到紧张。我有对象属性,它们是在这个例子中具有数组属性的对象列表。在某些情况下,依赖会走得更远。
是否Lock()“知道”需要锁定的所有内容?
还显示了下面脚本的输出。脚本的目的主要是为了讨论 - 它不会失败,但我不相信它会锁定它需要的一切。
start: [array([0, 1]), array([0, 1, 2]), array([0, 1, 2, 3])]
append an object
done!
finish: [array([505, 605]), array([10, 11, 12]), array([10, 11, 12, 13]), array([5])]
import time
from threading import Thread, Lock
import numpy as np
class Bucket(object):
def __init__(self, objects):
self.objects = objects
class Object(object):
def __init__(self, array):
self.array = array
class A(Thread):
def __init__(self, bucket):
Thread.__init__(self)
self.bucket = bucket
def run(self):
nloop = 0
locker …Run Code Online (Sandbox Code Playgroud) python ×8
concurrency ×2
python-2.7 ×2
joblib ×1
matplotlib ×1
mocking ×1
mysql-python ×1
pytest ×1
python-3.6 ×1
python-3.x ×1
queue ×1
reactivex ×1
rx-py ×1
threadpool ×1
tkinter ×1
unit-testing ×1