我有一个python类,我们称之为AClass,另一个是MyThread,它扩展了Thread.在那个AClass我创建MyThread类的2个对象,我也有一个信号量,我将它作为参数提供给MyThread类的构造函数.我的问题是,如果我修改一个MyThread对象中的信号量,另一个MyThread对象会看到差异吗?例如:
class AClasss:
def function:
semafor = threading.Semaphore(value=maxconnections)
thread1 = Mythread(semafor)
thread2 = Mythread(semafor)
thread1.start()
thread1.join()
thread2.start()
thread2.join()
class MyThread(Thread):
def __init__(self,semaphore):
self.semaphore = semaphore
def run():
semaphore.acquire()
"Do something here"
semaphore.release()
Run Code Online (Sandbox Code Playgroud)
那么thread1是否看到了thread2所做的信号量变化,反之亦然?
在Windows上使用python 2.7.4(注意:WinXP - 下面的评论者建议在Win7上正常工作),我有一个脚本创建几个线程,每个线程通过Popen运行子进程,stdout/stderr重定向到文件和调用等待().每个Popen都有自己的stdout/stderr文件.每个进程返回后,我有时必须删除文件(实际上将它们移动到其他地方).
我发现在所有wait()调用返回之前我都无法删除stdout/stderr日志.在此之前,我得到"WindowsError:[错误32]该进程无法访问该文件,因为它正被另一个进程使用".看起来,只要至少有一个子进程打开,Popen就会以某种方式保留stderr文件,即使这些文件没有共享.
测试代码重现如下.
C:\ test1.py
import subprocess
import threading
import os
def retryDelete(p, idx):
while True:
try:
os.unlink(p)
except Exception, e:
if "The process cannot access the file because it is being used by another process" not in e:
raise e
else:
print "Deleted logs", idx
return
class Test(threading.Thread):
def __init__(self, idx):
threading.Thread.__init__(self)
self.idx = idx
def run(self):
print "Creating %d" % self.idx
stdof = open("stdout%d.log" % self.idx, "w")
stdef = open("stderr%d.log" % self.idx, "w")
p = …Run Code Online (Sandbox Code Playgroud) python windows-xp subprocess python-multithreading python-2.7
import threading
threads = []
for n in range(0, 60000):
t = threading.Thread(target=function,args=(x, n))
t.start()
threads.append(t)
for t in threads:
t.join()
Run Code Online (Sandbox Code Playgroud)
它在我的笔记本电脑上的范围高达800,但是如果我将范围增加到800以上,我就会收到错误can't create new thread.
如何控制线程创建的数量或任何其他方式使其像超时一样工作?我尝试使用threading.BoundedSemaphore功能,但似乎没有正常工作.
我无法粘贴我的代码片段,所以我将解释方案1.我有一个大约50000个股票的列表,需要一些估价2.这些股票在MultiProcess.Queue 3.我创建多个流程,每个流程将从队列中取出一批50个并做一些事情.4.在主线程中,我有一张看起来像这样的支票
anymore_to_process = True
while anymore_to_process:
if (stock_queue.qsize() == 0):
anymore_to_process = False
for jobs in stock_jobs:
jobs.join()
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?当我处理大量股票时,为什么流程没有加入.
我知道如果不看我的代码就很难回答.....但如果你能给我一些指示,那将非常有帮助.
有关如何让我接受多个客户的任何帮助,以及为什么现在不是这样?谢谢!
另外,这个代码有什么问题吗?我一直在关注Python 2教程,因为我找不到任何Python 3.4
这是我的服务器代码:
import socket
import time
import os
from threading import Thread
folderPath = "Chat Logs"
filePath = folderPath + "/" + str(time.strftime("%H-%M-%S_%d-%m-%Y")) + ".txt"
def clientHandler(c):
while True:
data = c.recv(1024)
if not data:
break
data = data.decode("UTF-8")
message = str(data[:data.index("§")])
nick = str(data[data.index("§")+1:])
print(nick + ": " + message)
saveChat(nick, message)
print(" Sending: " + data)
c.send(bytes(data, "UTF-8"))
c.close()
def saveChat(nick, message):
if not os.path.exists(folderPath):
os.makedirs(folderPath)
if not os.path.exists(filePath):
f = open(filePath, "a")
f.close()
f …Run Code Online (Sandbox Code Playgroud) 我正在开发一个带有一些线程的应用程序,每个线程运行一个带有时间睡眠的无限循环.我想要的是在主要完成后完成所有线程,这里是一个例子:
def main():
display_res_stop = threading.Condition()
display_result_t = threading.Thread(target=sample_t, args=(display_res_stop, ))
display_result_t.start()
time.sleep(4)
display_res_stop.acquire()
display_res_stop.notify()
display_res_stop.release()
def sample_t(stop_cond):
stop_cond.acquire()
while True:
print 5
c = stop_cond.wait(10)
stop_cond.release()
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
这个解决方案的问题是我不知道condition.wait是否已经完成,因为超时或因为已经通知.在第二种情况下,while循环应该完成.
起初我正在做一个time.sleep(t)并使用线程事件但是应用程序必须等到所有线程都经过.
我正在考虑使用threading.Condition和Event的混合解决方案,但我不知道它是否是最好的事情(条件为'sleep'和Event替换为True).
我一直在使用concurrent.futures,因为它有一个简单的界面,让用户可以轻松控制线程/进程的最大数量.但是,似乎concurrent.futures隐藏了失败的任务,并在所有任务完成/失败后继续主线程.
import concurrent.futures
def f(i):
return (i + 's')
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
fs = [executor.submit(f, i ) for i in range(10)]
concurrent.futures.wait(fs)
Run Code Online (Sandbox Code Playgroud)
在任何整数上调用f都会导致TypeError.但是,整个脚本运行得很好,并以代码0退出.有没有办法让它在任何线程失败时抛出异常/错误?
或者,有没有更好的方法来限制线程/进程数量而不使用concurrent.futures?
python multithreading multiprocessing python-multithreading concurrent.futures
我有两个并行运行的函数,每个函数都返回一个值.我需要等待两个函数完成,然后处理它们的返回.我怎么能在python中实现这一点.假设
def fun1():
#do some calculation#
return val1
def fun2():
#do some calculation#
return val2
Run Code Online (Sandbox Code Playgroud)
我想fun1和fun2并行运行然后需要计算
valsum = val1+val2
Run Code Online (Sandbox Code Playgroud) 我正在学习Python中的线程库。我不明白,如何并行运行两个线程?
这是我的python程序:
没有线程的程序(fibsimple.py)
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
fib(35)
fib(35)
print "Done"
Run Code Online (Sandbox Code Playgroud)
运行时间:
$ time python fibsimple.py
Done
real 0m7.935s
user 0m7.922s
sys 0m0.008s
Run Code Online (Sandbox Code Playgroud)
带有线程的相同程序(fibthread.py)
from threading import Thread
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
t1 = Thread(target = fib, args = (35, ))
t1.start()
t2 = Thread(target = fib, args = (35, ))
t2.start()
t1.join()
t2.join()
print "Done"
Run Code Online (Sandbox Code Playgroud)
运行时间:
$ …Run Code Online (Sandbox Code Playgroud) python parallel-processing python-multithreading python-multiprocessing
我正在运行一个异步应用程序,该应用程序需要多个事件循环来服务大量的IO操作(同时进行上千个)。事件循环在单独的线程中运行,并在协程被提交时永久循环。
我正在寻找一种方法来识别现有事件循环何时接近满负荷,以便可以按需启动新的事件循环线程,而不是预先指定要运行的事件循环数。
接近容量意味着事件循环在80%的时间内忙碌。如果事件循环在等待状态下花费的时间少于其时间的20%,那么该添加另一个事件循环线程了。
每个线程似乎都不是那么容易:通过线程分析Python CPU使用情况