我在python文档中读到Queue.Queue()是一种在不同线程之间传递变量的安全方法.我真的不知道多线程存在安全问题.对于我的应用程序,我需要使用可以从多个不同线程访问的变量开发多个对象.现在我只是让线程直接访问对象变量.我不会在这里显示我的代码,因为它的方式太多了,但这里有一个例子来展示我正在做的事情.
from threading import Thread
import time
import random
class switch:
def __init__(self,id):
self.id=id
self.is_on = False
def self.toggle():
self.is_on = not self.is_on
switches = []
for i in range(5):
switches[i] = switch(i)
def record_switch():
switch_record = {}
while True:
time.sleep(10)
current = {}
current['time'] = time.srftime(time.time())
for i in switches:
current[i.id] = i.is_on
switch_record.update(current)
def toggle_switch():
while True:
time.sleep(random.random()*100)
for i in switches:
i.toggle()
toggle = Thread(target=toggle_switch(), args = ())
record = Thread(target=record_switch(), args = ())
toggle.start()
record.start()
Run Code Online (Sandbox Code Playgroud)
据我所知,队列对象只能用于放置和获取值,这显然不适用于我.我在这里"安全"吗?如果没有,我该如何编程,以便我可以安全地从多个不同的线程访问变量?
我似乎无法创建一个mongoDB数据库.我读过4个教程,看起来应该很直接.我错过了什么吗?我的安装有什么问题吗?
> use a
switched to db a
> a.abc.save({abc:"asdf"})
2015-04-17T01:39:45.723-0400 E QUERY ReferenceError: a is not defined
at (shell):1:1
> a.abc.insert({abc:"asdf"})
2015-04-17T01:39:58.572-0400 E QUERY ReferenceError: a is not defined
at (shell):1:1
Run Code Online (Sandbox Code Playgroud)