def __init__(self, room_name): self.name = room_name self.ref = chat_server.number_of_rooms self.member_IDs = [] chat_server.number_of_rooms += 1 self.lock = threading._RLock() logging.info("{} created".format(room_name))
def __init__(self, *args): from OpenSSL import SSL as _ssl self._ssl_conn = apply(_ssl.Connection, args) from threading import _RLock self._lock = _RLock()
def __init__(self, room_name): self.name= room_name self.ref=chat_server.number_of_rooms self.member_IDs = [] chat_server.number_of_rooms+=1 self.lock=threading._RLock() logging.info("{} created".format(room_name))
def __init__(self): self.mutex = _RLock() self.total_size = 0 self.curr_size = 0 self.last_size = 0 self.last_updat_at = 0 self.start_at = 0 self.sub_bar_count = 0 self.__echo_bak = self.echo
def __init__(self): self.mutex = _RLock() self.total_size =0 self.curr_size =0 self.last_size = 0 self.last_updat_at = 0 self.start_at = 0 self.sub_bar_count = 0 self.__echo_bak = self.echo
def __init__(self, win, window_title, video_source=0): self.win = win self.win.title(window_title) self.win_width, self.win_height = self.set_screen_size(self.win) self.screen_width = self.win.winfo_screenwidth() self.screen_height = self.win.winfo_screenheight() self.canvas_width = int(4 * self.win_height / 5) self.canvas_height = int(3 * self.win_height / 5) self.screen_ratio = 1.2 # 用于调整不同屏幕分辨率时 界面大小 self.win.resizable(0, 0) #窗口不可调节大小 self.video_source = video_source # open video source self.vid = widgets.MyVideoCapture(self.canvas_width, self.canvas_height) self.widfun = widgets.WidFun() self.pic_group_flag = 1 # 用于标记各组照片的组号 self.pic_group_flag_pic_flag = 1 # 用于标记单组内的图片编号 #self.read_flag = '' 读取文件用 self.pic_sum = 0 self.delay = 40 #视频刷新delay 1000/dely = 帧数 self.pic_count = 0 #读取的原始图片 self.defect_pic_count = 0 # 循环播放缺陷图片用初始0 self.pic_seq = 0 # 上下键对比播放图片计数 self.defect_count = 0 # 缺陷计数 self.defect_src_list = [] # 存在缺陷的原图 self.defect_info_list = [] self.COM = None #self.COM = serial.Serial('COM1',9600,bytesize=8,stopbits=1,parity='N',timeout=0.5) self.state_read_flag = Event() # 设置平台读取状态开关 self.state_read_flag.set() # 将读取开关设置为true self.platform_position = 0 self.platform_state = 0 self.lock = _RLock() # 总计重复自动拍照 次数 self.timer_interval = 0 # 两次间隔拍照之间的时间 self.timer_times_count = 0 # 自动拍照计数 #放置组件 self.create_tab() self.create_menu() self.create_widgets() # 第一页 视频显示 图像采集页 self.create_widgets_2() # 第二页 图像播放 参数设置页 #self.create_widgets_3() # 第三页 缺陷信息汇总页 self.widfun.defaultFileEntries( fileEntry=self.fileEntry, dstEntry=self.dstEntry, snapPathEntry=self.snapPathEntry) #设置初始路径 self.plt_setting() self.receive_state_thread() #self.read_log_thread() # 开启线程 监控log文件 #self.put_defect_img() self.draw_RGB() self.update_cam() self.win.mainloop()
def __init__(self): self._lock = threading._RLock() self.boardWidth = 10 self.boardHeight = 10 self.boards = [[[" " for _ in range(self.boardWidth)] for _ in range(self.boardHeight)] for _ in range(2)] # two 10x10 boards self.numShipcells = [0, 0] self.players = [] self.activePlayer = None self.turn = None self.gameReady = threading.Event() self.ships = [0, 1, 2, 1, 1] self.playersReady = 0 self.result = None
def __init__(self, fget=None, fset=None, fdel=None, doc=None): doc = doc or fget.__doc__ super(cachedproperty, self).__init__(fget, None, None, doc) if fget is None: self._func = None self._func_name = '' else: self._func = fget self._func_name = self._func.__name__ _update_wrapper(self, fget) self._lock = _RLock()
def __init__(self, fget=None, fset=None, fdel=None, doc=None): if fset is not None or fdel is not None: raise AttributeError( 'Cached properties cannot implement set and delete methods.') if doc is None and fget is not None: doc = fget.__doc__ super().__init__(fget, fset, fdel, doc) self._func = fget self._func_name = None self._lock = _RLock() _ft_update_wrapper(self, fget)
def __init__(self, win, window_title, video_source=0): self.win = win self.win.title(window_title) self.win_width, self.win_height = self.set_screen_size( self.win) #设置gui self.canvas_width = int(4 * self.win_height / 5) #设置所有画布的宽高 self.canvas_height = int(3 * self.win_height / 5) self.win.resizable(0, 0) #窗口不可调节大小 self.video_source = video_source # open video source self.vid = widgets.MyVideoCapture(self.canvas_width, self.canvas_height) self.widfun = widgets.WidFun() #实例化widgets里的函数 self.pic_sum = 0 #记录从软件运行开始拍摄照片的数量 self.delay = 40 #视频刷新delay 1000/dely = 帧数 self.pic_count = 0 #读取的原始图片 self.defect_pic_count = 0 # 循环播放缺陷图片用初始0 self.pic_seq = 0 # 上下键对比播放图片计数 self.defect_count = 0 # 缺陷计数 self.defect_src_list = [] # 存在缺陷的原图 self.defect_dst_list = [] # 存在缺陷的dst图 self.defect_info_list = [] self.COM_plc = None #self.COM = serial.Serial('COM1',9600,bytesize=8,stopbits=1,parity='N',timeout=0.5) self.state_read_flag = Event() # 设置平台读取状态开关 self.state_read_flag.set() # 将读取开关设置为true self.platform_position = 0 self.platform_state = 0 self.lock = _RLock() # 总计重复自动拍照 次数 self.timer_interval = 0 # 两次间隔拍照之间的时间 self.timer_times_count = 0 # 自动拍照计数 #放置组件 self.create_tab() self.create_menu() self.create_widgets() # 第一页 视频显示 图像采集页 self.create_widgets_2() # 第二页 图像播放 参数设置页 #self.create_widgets_3() # 第三页 缺陷信息汇总页 self.widfun.defaultFileEntries( fileEntry=self.fileEntry, dstEntry=self.dstEntry, snapPathEntry=self.snapPathEntry) #设置初始路径 self.plt_setting() self.draw_RGB() self.update_cam() self.win.mainloop()
def __init__(self, win, window_title,video_source = 0): self.win = win self.win.title(window_title) self.win.geometry('1120x630') self.win.resizable(0, 0) #窗口不可调节大小 self.video_source = video_source # open video source self.vid = MyVideoCapture() self.pic_group_flag = 1 # 用于标记各组照片的组号 self.pic_group_flag_pic_flag = 1 # 用于标记单组内的图片编号 #self.read_flag = '' 读取文件用 self.pic_sum = 0 self.delay = 40 #视频刷新delay 1000/dely = 帧数 self.pic_count = 0 #读取的原始图片 self.defect_pic_count = 0 # 循环播放缺陷图片用初始0 self.pic_seq = 0 # 上下键对比播放图片计数 self.defect_count = 0 # 缺陷计数 self.defect_src_list = [] # 存在缺陷的原图 self.defect_info_list=[] self.COM = None #self.COM = serial.Serial('COM1',9600,bytesize=8,stopbits=1,parity='N',timeout=0.5) self.state_read_flag = Event() # 设置平台读取状态开关 self.state_read_flag.set() # 将读取开关设置为true self.platform_position = 0 self.platform_state = 0 self.lock = _RLock() # 总计重复自动拍照 次数 self.timer_interval = 0 # 两次间隔拍照之间的时间 self.timer_times_count = 0 # 自动拍照计数 #放置组件 self.create_tab() self.create_menu() self.create_widgets() # 第一页 视频显示 图像采集页 self.create_widgets_2() # 第二页 图像播放 参数设置页 self.create_widgets_3() # 第三页 缺陷信息汇总页 self.defaultFileEntries() self.receive_state_thread() #self.read_log_thread() # 开启线程 监控log文件 #self.put_defect_img() self.update_thread() self.win.mainloop()
def __init__(self, name: str, cfg: dict, app: "SchedyApp") -> None: self.name = name self.cfg = cfg self.app = app self.actors = [] # type: T.List[ActorBase] self.schedule = None # type: T.Optional[schedule.Schedule] self._actor_wanted_values = {} # type: T.Dict[ActorBase, T.Any] self._wanted_value = None # type: T.Any self._scheduled_value = None # type: T.Any self._rescheduling_time = None # type: T.Optional[datetime.datetime] self._rescheduling_timer = None # type: T.Optional[uuid.UUID] self._overlaid_wanted_value = None # type: T.Any self._overlaid_scheduled_value = None # type: T.Any self._overlaid_rescheduling_time = None # type: T.Optional[datetime.datetime] self._last_state = None # type: T.Optional[T.Tuple[str, T.Dict[str, T.Any]]] self._sync_proxy_lock = threading._RLock() # pylint: disable=protected-access self._sync_proxy_running = False
def __init__(self, count=0, group=None, target=None, args=(), kwargs=None, name=None, verbose=None): super(myThread, self).__init__(group=None, target=None, args=(), kwargs=None, name=None, verbose=None) self.var = count self.args = args self.kwargs = kwargs self.items = [] self.semaphore = threading.Semaphore() self.lock = threading._RLock()
from app.mqtt import publish, connect, subscribe from app.mirror.weather_display import WeatherFeed from app.mirror.news_display import NewsFeed from app.mirror.notes_display import NotesFeed from app.mirror.welcome_display import WelcomeFeed from app.mirror.camera_display import CameraFeed from threading import _RLock import traceback import time import json import flicklib from Tkinter import * from ttk import * # variables for lock and client for symmetry throughout app lock = _RLock() mqtt_client = connect.get_client() # array of displays displays = [] # initialise ready variable to False until system is ready ready = False # callback for /iotappdev/pi/auth/ # - makes sure current display is welcome_display # - checks if received auth number is correct # * if correct call change display method with 0 direction and publish authorised to AWS # * if not correct publish unauthorised to AWS # - asyn publishing used so that callback does not continually publish def auth_callback(client, userdata, message): try:
import socket from array import * import sys import time from _thread import * import threading import random # lock = threading._RLock() # listening_port = 0 lock_stop_seeds = threading._RLock() lock_seed_sockets = threading._RLock() lock_local_clients = threading._RLock() lock_all_clients = threading._RLock() seed_sockets = [] local_clients = [] all_clients = [] stop_seeds = False def seed_receive_thread(c): global all_clients # global seed_sockets global stop_seeds data = "" while True: while True: data = c.recv(1024) # print("data received: "+data.decode('ascii')) if(data.decode('ascii') == "no seeds"): print("no more seeds, inverting stop_seeds")
class _ReloadableSingleton(object): __facades = [] __lock = _RLock() def __getattr__(self, name): if self.__instance is None: self.__lock.acquire() try: self.__realize() finally: self.__lock.release() result = getattr(self.__instance, name) return result def __setattr__(self, name, value): if self.__instance is None: self.__lock.acquire() try: self.__realize() finally: self.__lock.release() return setattr(self.__instance, name, value) def __setitem__(self, name, value): if self.__instance is None: self.__lock.acquire() try: self.__realize() finally: self.__lock.release() result = self.__instance.__setitem__(name, value) return result def __getitem__(self, name): if self.__instance is None: self.__lock.acquire() try: self.__realize() finally: self.__lock.release() result = self.__instance.__getitem__(name) return result def __init__(self, klass, *args, **keywords): self.__dict__['_ReloadableSingleton__klass'] = klass self.__dict__['_ReloadableSingleton__args'] = args self.__dict__['_ReloadableSingleton__keywords'] = keywords self.__dict__['_ReloadableSingleton__instance'] = None self.__dict__['_ReloadableSingleton__loadable'] = True self.__lock.acquire() try: self.__facades.append(self) finally: self.__lock.release() return def __str__(self): return str(self.__instance) def __repr__(self): return repr(self.__instance) def __realize(self): if not self.__instance is None: return if not self.__loadable: raise ELoadingDisabled("Instance currently not loadable.") instance = self.__klass(*self.__args, **self.__keywords) assert hasattr(instance, 'singleton_unload_hook'), ( "ReloadableSingletonInterface requires a singleton_unload_hook" " method.") self.__dict__['_ReloadableSingleton__instance'] = instance return def __unrealize(self): if self in self.__facades: if not self.__instance is None: self.__instance.singleton_unload_hook() self.__dict__['_ReloadableSingleton__instance'] = None return ## # Realize an actual instance of this singleton. If the instance is already # realized, then do nothing. def singleton_load(self): self.__lock.acquire() try: self.__realize() finally: self.__lock.release() return ## # Force the underlying instance of the singleton to be unrealized. If the # instance is already unrealized, then do nothing. def singleton_unload(self): self.__lock.acquire() try: self.__unrealize() finally: self.__lock.release() return ## # Set the loadable state of a singleton. This state stays in effect until # changed by a subsequent call. This does not change the whether or not # the instance is actually already loaded not access to the actual instance # if it is loaded. # # @param loadable Boolean indicating whether to allow loading of the actual # instance of a singleton's facade. def singleton_set_loadable_state(self, loadable): self.__lock.acquire() try: was_loadable = self.__loadable self.__dict__['_ReloadableSingleton__loadable'] = loadable finally: self.__lock.release() return was_loadable ## # Class method that will search for a specific facade and unrealize its # actual instance. # # @param instance_facade The facade to the actual instance to unload. def singleton_unload_by_facade(klass, instance_facade): klass.__lock.acquire() try: facades = [] facades.extend(klass.__facades) for facade in facades: if facade is instance_facade: facade.__unrealize() return 1 finally: klass.__lock.release() return 0 singleton_unload_by_facade = classmethod(singleton_unload_by_facade) ## # Class method that will search for a specific instance in the list of all # singleton facades and unrealize it. # # @param actual_instance The underlying instance to a singleton facade. # @note Typically, only an underlying instance would use this. And it's # a bit of a hack - too much coupling. def singleton_unload_by_instance(klass, actual_instance): klass.__lock.acquire() try: facades = [] facades.extend(klass.__facades) for facade in facades: if facade.__instance is actual_instance: facade.__unrealize() return 1 finally: klass.__lock.release() return 0 singleton_unload_by_instance = classmethod(singleton_unload_by_instance) ## # Class method that will unload all singleton's underlying actual # instances. def singleton_unload_all(klass): klass.__lock.acquire() try: facades = [] facades.extend(klass.__facades) for facade in facades: facade.__unrealize() finally: klass.__lock.release() return singleton_unload_all = classmethod(singleton_unload_all) ## # Class method that will apply a LOADABLE state to all currently existing # singletons. This does not change the whether or not # the instance is actually already loaded not access to the actual instance # if it is loaded. # # @param loadable Boolean indicating whether to allow loading of the actual # instances of the singletons' facades. def singleton_set_loadable_state_all(klass, loadable): klass.__lock.acquire() try: facades = [] facades.extend(klass.__facades) for facade in facades: facade.singleton_set_loadable_state(loadable) finally: klass.__lock.release() return singleton_set_loadable_state_all = classmethod( singleton_set_loadable_state_all) import edtlib as _edtlib def _edt_encode(cls, rso): o = rso.__instance encoder = cls._edtlib.codec_map.lookup(o).encoder return encoder(o) _edt_encode = classmethod(_edt_encode) def _edt_register(cls): return cls._edtlib.register_class(cls, decoder=None, encoder=cls._edt_encode) _edt_register = classmethod(_edt_register)
print(self.name, 'got B at', time.ctime()) time.sleep(2) r_lock.acquire() print(self.name, 'got A at', time.ctime()) time.sleep(1) r_lock.release() r_lock.release() def run(self): self.actionA() self.actionB() if __name__ == '__main__': # A = threading.Lock() # B = threading.Lock() r_lock = threading._RLock() # 遞歸鎖 l = [] for i in range(5): t = Mythread() t.start() l.append(t) for i in l: i.join() print('end')
class GLOBAL(object): """ datetime.strptime 有线程安全问题""" dt_lock = threading._RLock()
_parse_pattern, _shrink_cache) from _regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source as _Source, Fuzzy as _Fuzzy) # Version 0 is the old behaviour, compatible with the original 're' module. # Version 1 is the new behaviour, which differs slightly. DEFAULT_VERSION = VERSION0 _METACHARS = frozenset("()[]{}?*+|^$\\.-#&~") _regex_core.DEFAULT_VERSION = DEFAULT_VERSION # Caches for the patterns and replacements. _cache = {} _cache_lock = _RLock() _named_args = {} _replacement_cache = {} _locale_sensitive = {} # Maximum size of the cache. _MAXCACHE = 500 _MAXREPCACHE = 500 def _compile(pattern, flags=0, kwargs={}): "Compiles a regular expression to a PatternObject." # We won't bother to cache the pattern if we're debugging. debugging = (flags & DEBUG) != 0 # What locale is this pattern using?
def __init__(self, timeout: int = -1, name: Optional[str] = None): self._lock = _RLock() self.timeout = timeout self.name = name
def __init__(self): self.lock = _RLock() self.mqtt_client = connect.get_client(self.mqtt_client)
return (abc.blockhash + ":" + abc.merkelroot + ":" + str(abc.timestamp)).encode('ascii') import socket import sys import threading import fcntl, errno, os import time from datetime import datetime import random import hashlib import numpy as np ## common sockets array used by all threads lock = threading._RLock() socks = [] message_list = [] mining_lock = threading._RLock() mining_to_start = False time_lock = threading._RLock() header_list_lock = threading._RLock() block_header_list = [] received_lock = threading._RLock() received_block = 0 last_hash_lock = threading._RLock() last_block_hash = '9e1c' genesis_block = '9e1c' total_clients = 0 total_cl_lock = threading._RLock() longest_chain_length = 1
import time import threading mutex = threading._RLock() count = 0 class MyThread(threading.Thread): def run(self): global count time.sleep(1) if mutex.acquire(): for i in range(100): count = count + 1 print 'thread{} add 1,count is {} \n'.format(self.name,count) mutex.release() def main(): print 'start main threading' threads=[MyThread() for i in range(10)] for t in threads: t.start() # for t in threads: # t.join(3) print 'end main threading' if __name__=='__main__': main()
def decorating_function(user_function): cache = dict() stats = [0, 0] # make statistics updateable non-locally HITS, MISSES = 0, 1 # names for the stats fields make_key = _make_key cache_get = cache.get # bound method to lookup key or return None _len = len # localize the global len() function lock = _RLock() # because linkedlist updates aren't threadsafe root = [] # root of the circular doubly linked list root[:] = [root, root, None, None] # initialize by pointing to self nonlocal_root = [root] # make updateable non-locally PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields if maxsize == 0: def wrapper(*args, **kwds): # no caching, just do a statistics update after a successful call result = user_function(*args, **kwds) stats[MISSES] += 1 return result elif maxsize is None: def wrapper(*args, **kwds): # simple caching without ordering or size limit key = make_key(args, kwds, typed) result = cache_get(key, root) # root used here as a unique not-found sentinel if result is not root: stats[HITS] += 1 return result result = user_function(*args, **kwds) cache[key] = result stats[MISSES] += 1 return result else: # noinspection PyShadowingNames def wrapper(*args, **kwds): # size limited caching that tracks accesses by recency key = make_key(args, kwds, typed) if kwds or typed else args with lock: link = cache_get(key) if link is not None: # record recent use of the key by moving it to the front of the list root, = nonlocal_root link_prev, link_next, key, result = link link_prev[NEXT] = link_next link_next[PREV] = link_prev last = root[PREV] last[NEXT] = root[PREV] = link link[PREV] = last link[NEXT] = root stats[HITS] += 1 return result result = user_function(*args, **kwds) with lock: root, = nonlocal_root if key in cache: # getting here means that this same key was added to the # cache while the lock was released. since the link # update is already done, we need only return the # computed result and update the count of misses. pass elif _len(cache) >= maxsize: # use the old root to store the new key and result oldroot = root oldroot[KEY] = key oldroot[RESULT] = result # empty the oldest link and make it the new root root = nonlocal_root[0] = oldroot[NEXT] oldkey = root[KEY] # oldvalue = root[RESULT] root[KEY] = root[RESULT] = None # now update the cache dictionary for the new links del cache[oldkey] cache[key] = oldroot else: # put result in a new link at the front of the list last = root[PREV] link = [last, root, key, result] last[NEXT] = root[PREV] = cache[key] = link stats[MISSES] += 1 return result def cache_info(): """Report cache statistics""" with lock: return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache)) # noinspection PyShadowingNames def cache_clear(): """Clear the cache and cache statistics""" with lock: cache.clear() root = nonlocal_root[0] root[:] = [root, root, None, None] stats[:] = [0, 0] wrapper.__wrapped__ = user_function wrapper.cache_info = cache_info wrapper.cache_clear = cache_clear return update_wrapper(wrapper, user_function)
from threading import Event,_RLock import threading class a(threading.Thread): def run(self): r.wait(2) print(threading.currentThread().getName()) r1.acquire() for i in range(0,5): print(threading.currentThread().getName(),i) r1.release() threads=[] r=Event() r1=_RLock() t=a() t1=a() t2=a() t3=a() t.setName('ab') t1.setName('cd') t2.setName('ef') t3.setName('gh') t.start() t1.start() t2.start() t3.start() threads.append(t) threads.append(t1) threads.append(t2) threads.append(t3) for i in threads: i.join()
def __init__(self): self.__mutex = _RLock() self.hfile = None
def __init__(self, *args): self._ssl_conn = _ssl.Connection(*args) self._lock = _RLock()
def __init__(self, hostspec): self.socket = _ConnectToMds(_ver.tobytes(hostspec)) if self.socket == -1: raise MdsIpException("Error connecting to %s" % (hostspec, )) self.hostspec = hostspec self.lock = _RLock()
_parse_pattern, _shrink_cache) from _regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source as _Source, Fuzzy as _Fuzzy) # Version 0 is the old behaviour, compatible with the original 're' module. # Version 1 is the new behaviour, which differs slightly. DEFAULT_VERSION = VERSION0 _METACHARS = frozenset("()[]{}?*+|^$\\.") _regex_core.DEFAULT_VERSION = DEFAULT_VERSION # Caches for the patterns and replacements. _cache = {} _cache_lock = _RLock() _named_args = {} _replacement_cache = {} _locale_sensitive = {} # Maximum size of the cache. _MAXCACHE = 500 _MAXREPCACHE = 500 def _compile(pattern, flags=0, kwargs={}): "Compiles a regular expression to a PatternObject." # We won't bother to cache the pattern if we're debugging. debugging = (flags & DEBUG) != 0 # What locale is this pattern using?
''' 一个子线程A把一个全局的列表words进行升序的排序,另外一个D线程把这个列表进行降序的排列 ''' import threading import time lock = threading._RLock() words = ['a', 'g', 'c', 'd', 'e', 'f', 'b'] def increase(): time.sleep(1) global words for count in range(5): lock.acquire() # 获取对锁的控制权 print('A acquire') words = sorted(words, reverse=True) print('A', words) # time.sleep(1) lock.release() def decrease(): time.sleep(1) global words for count in range(5): lock.acquire() # 获取对锁的控制权 print('D acquire') words = sorted(words, reverse=False) print('D', words) # time.sleep(1)
return (abc.blockhash + abc.merkelroot + str(abc.timestamp)).encode('ascii') def preparetosend(abc): return (abc.blockhash + ":" + abc.merkelroot + ":" + str(abc.timestamp)).encode('ascii') import socket import sys import threading import fcntl, errno, os import time from datetime import datetime import random import hashlib import numpy as np ## common sockets array used by all threads lock = threading._RLock() socks = [] message_list = [] mining_lock = threading._RLock() mining_to_start = False time_lock = threading._RLock() header_list_lock = threading._RLock() block_header_list = [] received_lock = threading._RLock() received_block = 0 last_hash_lock = threading._RLock() last_block_hash = '9e1c' genesis_block = '9e1c' total_clients = 0 total_cl_lock = threading._RLock() longest_chain_length = 1
def __init_new__(self, *args, **kargs): __init_old__(self, *args, **kargs) self._rlock = _RLock()