我在停止正在执行阻塞操作的线程时遇到问题。我正在编写一个使用gpsd及其python绑定的程序,该Thread的run方法如下所示:
def run(self):
print "inside run. outside while"
global gpsd
while self.running:
print "inside while"
try:
print "before next()"
gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
print "after next()"
self.file_descriptor.write(str(int(time.time())) + ',' + str(gpsd.fix.latitude) + ',' + str(gpsd.fix.longitude) + ',' + str(gpsd.fix.altitude) + ',' + str(gpsd.fix.speed) + '\n')
print "after write"
#self.file_descriptor.write("self.running" + str(self.running) + '\n')
self.file_descriptor.flush()
print "after flush"
time.sleep(5)
print "after sleep"
except:
print "inside thread except"
raise …Run Code Online (Sandbox Code Playgroud) 我如何检查主线程是否从另一个(非守护程序,子线程)线程还存在?
子线程是非守护线程,我想检查Main线程是否仍在运行,并根据结果停止该非守护线程。
(使线程守护程序不适用于我的情况,因为stdout当线程设置为守护程序时,我的线程写入该线程会产生问题)
使用python 2.7
用于添加和删除列表中的值的代码是在不同线程中执行的操作.
在多线程中使用这些全局变量:
from threading import Thread
import time
a=[]
i = 0
j = 0
Run Code Online (Sandbox Code Playgroud)
thread1的函数:
def val_in():
while 1:
a.append(raw_input())
print "%s value at %d: %d added" % ( time.ctime(time.time()), i ,int(a[i])) // line 14
i+=1
Run Code Online (Sandbox Code Playgroud)
线程2的功能:
def val_out():
while 1:
time.sleep(5)
try:
print "%s value at %d: %d deleted" % (time.ctime(time.time()), j, int(a.pop(j)))
i-=1
except:
print"no values lefts"
time.sleep(2)
Run Code Online (Sandbox Code Playgroud)
定义和启动线程:
t = Thread(target = val_in)
t1 = Thread(target= val_out)
t.start()
t1.start()
Run Code Online (Sandbox Code Playgroud)
现在当输入为1,它应该被添加到列表中a,但是有一个错误:
Error: Exception …Run Code Online (Sandbox Code Playgroud) 我有一个Producer和一个Consumer线程(threading.Thread),它共享一个queue类型Queue.
制片人run:
while self.running:
product = produced() ### I/O operations
queue.put(product)
Run Code Online (Sandbox Code Playgroud)
消费者run:
while self.running or not queue.empty():
product = queue.get()
time.sleep(several_seconds) ###
consume(product)
Run Code Online (Sandbox Code Playgroud)
现在我需要终止主线程中的两个线程,并且queue在终止之前必须为空(全部已消耗)的要求.
目前我正在使用如下代码来终止这两个线程:
主线程stop:
producer.running = False
producer.join()
consumer.running = False
consumer.join()
Run Code Online (Sandbox Code Playgroud)
但我想如果有更多的消费者,这是不安全的.
另外,我不确定是否sleep会向制作人发布时间表以便它可以生产更多产品.事实上,我发现生产者一直"挨饿",但我不确定这是否是根本原因.
有没有一个体面的方法来处理这个案子?
python multithreading producer-consumer python-multithreading
我很好奇是否可以将函数f(x,y)的返回值附加到例如list中.
所以我有这个:
平行:
def download_unit_LVs(self, cislo_uzemia):
pool = Pool(number_of_workers)
for cislo in cisla:
pool.apply_async(self.download_cislo, args=(cislo_uzemia,cislo))
pool.close()
pool.join()
self.manager.commit()
Run Code Online (Sandbox Code Playgroud)
这是我运行方法self.download_cislo并行的方法,但问题是,它返回一个我必须附加到结果列表的值.
怎么做?
顺序:
def download_unit_LVs(self, cislo_uzemia):
results = []
for cislo in cisla:
results.append(self.download_cislo(cislo_uzemia,cislo))
self.manager.commit()
Run Code Online (Sandbox Code Playgroud) 我正在使用基本线程.这是我输入的代码.
#!usr/bin/python3
import threading
class Bhai_ka_messenger(threading.Thread):
def run(self):
for message in range(10):
print threading.currentThread().getName()
a=Bhai_ka_messenger(name="message send")
b=Bhai_ka_messenger(name="message receive")
a.start()
b.start()
Run Code Online (Sandbox Code Playgroud)
这说模块对象没有属性线程.当我在在线IDE上运行它时,该程序可以正常工作.现在我无法解决这个问题,任何人都可以帮忙吗?
我在一个类的许多实例之间共享一个计数器(training_queue).该类继承了threading.Thread,因此它实现了run()方法.当我调用start()时,我希望每个线程都增加这个计数器,所以当它达到一个限制时,不再启动线程.但是,没有一个线程修改变量.这是代码:
class Engine(threading.Thread):
training_mutex = threading.Semaphore(MAX_TRAIN)
training_queue = 0
analysis_mutex = threading.Semaphore(MAX_ANALYSIS)
analysis_queue = 0
variable_mutex = threading.Lock()
def __init__(self, config):
threading.Thread.__init__(self)
self.config = config
self.deepnet = None
# prevents engine from doing analysis while training
self.analyze_lock = threading.Lock()
def run(self):
with self.variable_mutex:
self.training_queue += 1
print self.training_queue
with self.training_mutex:
with self.analyze_lock:
self.deepnet = self.loadLSTM3Model()
Run Code Online (Sandbox Code Playgroud)
我使用Lock保护training_queue,因此它应该是线程安全的.但是,如果我总是打印它的值1.在这种情况下,线程如何影响变量范围?
我正在创建一个函数将文件从本地机器复制到远程创建线程并行执行sftp
def copyToServer():
//does copy file given host name and credentials
for i in hostsList:
hostname = i
username = defaultLogin
password = defaultPassword
thread = threading.Thread(target=copyToServer, args=(hostname, username, password, destPath, localPath))
threadsArray.append(thread)
thread.start()
Run Code Online (Sandbox Code Playgroud)
这会创建线程并开始并行复制但我想限制它一次处理50个线程,因为服务器总数可能太多
我运行了这段代码
NUM = 0
def count():
global NUM
NUM += 1
time.sleep(1)
print(t.getName()+":"+"NUM is "+str(NUM))
for i in range(10):
t = threading.Thread(target=count)
t.start()
Run Code Online (Sandbox Code Playgroud)
输出是
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Run Code Online (Sandbox Code Playgroud)
我知道为什么NUM总是10,但为什么线程名称总是相同的?每个线程运行print(t.getName()+":"+"NUM is "+str(NUM)); 的t不应该是得到的CPU时间的一个线程?我认为这个名字不应该是一样的.
当我改变这个
NUM = 0
def count():
global NUM
NUM += 1
name = t.getName()
time.sleep(1)
print(name+":"+"NUM is "+str(NUM)) …Run Code Online (Sandbox Code Playgroud) import multiprocessing
q = multiprocessing.Queue()
def create_jobs():
for link in file_to_set(QUEUE_FILE):
q.put(link)
q.join() **#here i'm getting Attribute Error**
crawl()
Run Code Online (Sandbox Code Playgroud)
(这不是完整的代码段。但是我的函数仅在此处给出错误。)