def __init__(self, receive_callback, connect_helper): self._host = "" self._port = -1 self._cafile = "" self._key = "" self._cert = "" self._sock = None self._output_queue_size = -1 self._output_queue_dropbehavior = -1 self._mqttOperationTimeout = 5 self._connection_state = mqttConst.STATE_DISCONNECTED self._conn_state_mutex = _thread.allocate_lock() self._poll = select.poll() self._output_queue = [] self._out_packet_mutex = _thread.allocate_lock() _thread.stack_size(8192) _thread.start_new_thread(self._io_thread_func, ()) self._recv_callback = receive_callback self._connect_helper = connect_helper self._pingSent = False self._ping_interval = 20 self._waiting_ping_resp = False self._ping_cutoff = 3 self._receive_timeout = 3000 self._draining_interval = 2 self._draining_cutoff = 3 self._shadow_cb_queue = [] self._shadow_cb_mutex = _thread.allocate_lock()
def test_stack_size(self): # Various stack size tests. self.assertEqual(thread.stack_size(), 0, "initial stack size is not 0") thread.stack_size(0) self.assertEqual(thread.stack_size(), 0, "stack_size not reset to default")
def StartManaged(self, parllProcCount=1, procStackSize=0): if not isinstance(parllProcCount, int) or parllProcCount < 0: raise ValueError( '"parllProcCount" must be a positive integer or zero.') if not isinstance(procStackSize, int) or procStackSize < 0: raise ValueError( '"procStackSize" must be a positive integer or zero.') if self._xasSrv: raise MicroWebSrv2Exception('Server is already running.') if procStackSize == 0 and implementation.name == 'micropython': procStackSize = 8 * 1024 try: saveStackSize = stack_size(procStackSize) except Exception as ex: raise ValueError('"procStackSize" of %s is not correct (%s).' % (procStackSize, ex)) self._xasPool = XAsyncSocketsPool() try: self.StartInPool(self._xasPool) try: self.Log('Starts the managed pool to wait for I/O events.', MicroWebSrv2.INFO) self._xasPool.AsyncWaitEvents(threadsCount=parllProcCount) except: raise MicroWebSrv2Exception( 'Not enough memory to start %s parallel processes.' % parllProcCount) except Exception as ex: self.Stop() raise ex finally: try: stack_size(saveStackSize) except: pass
def main(): # 全局变量 global disp, frame, detected, plateNumber frame = None detected = False plateNumber = None # 创建lcd display对象 disp = display.TFT() # 连接网络 connect_wifi(SSID, PWD) # 初始化摄像头 ucamera.init('uart', 33, 32) ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240) try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 设置车牌识别线程stack _thread.stack_size(15 * 1024) # 启动车牌识别线程 _thread.start_new_thread(recognizePlateLicenceThread, ()) except: print("Error: unable to start thread") # 主线程IDLE while True: utime.sleep_ms(1000)
def test_stack_size(): import sys if is_cli or (sys.version_info[0] == 2 and sys.version_info[1] > 4) or sys.version_info[0] > 2: import _thread size = _thread.stack_size() Assert(size == 0 or size >= 32768) bad_size_list = [1, -1, -32768, -32769, -32767, -40000, 32767, 32766] for bad_size in bad_size_list: AssertError(ValueError, _thread.stack_size, bad_size) good_size_list = [4096 * 10, 4096 * 100, 4096 * 1000, 4096 * 10000] for good_size in good_size_list: #CodePlex Work Item 7827 if (is_cli or is_silverlight) and good_size <= 50000: print("Ignoring", good_size, "for CLI") continue temp = _thread.stack_size(good_size) Assert(temp >= 32768 or temp == 0) def temp(): pass _thread.start_new_thread(temp, ()) temp = _thread.stack_size(1024 * 1024) Assert(temp >= 32768 or temp == 0)
def __init__(self, workersCount, workersStackSize=None): self._workersCount = workersCount self._workersLock = _thread.allocate_lock() self._jobsLock = _thread.allocate_lock() self._jobsPrcCount = 0 self._jobs = [] originalStackSize = None if not isinstance(workersCount, int) or workersCount <= 0: raise MicroWorkersException( '"workersCount" must be an integer greater than zero.') if workersStackSize is not None: if not isinstance(workersStackSize, int) or workersStackSize <= 0: raise MicroWorkersException( '"workersStackSize" must be an integer greater than zero or None.' ) try: originalStackSize = _thread.stack_size(workersStackSize) except: raise MicroWorkersException( '"workersStackSize" of %s cannot be used.' % workersStackSize) try: for x in range(workersCount): _thread.start_new_thread(self._workerThreadFunc, (None, )) except Exception as ex: raise MicroWorkersException('Error to create workers : %s' % ex) if originalStackSize is not None: _thread.stack_size(originalStackSize)
def start_http(self): _thread.stack_size(6 * 1024) # gc.collect() self._http_thread = _thread.start_new_thread("HtppSe", self._run_http_process, ())
def run_script_threaded(filename): try: thread.stack_size(5*1024) thread.allowsuspend(True) file = open(filename) content = file.read() file.close() fix = '''while True: ntf = thread.getnotification() if ntf: if ntf == thread.EXIT: sys.exit() elif ntf == thread.SUSPEND: while thread.wait() != thread.RESUME: pass''' content = content.replace('while True:', fix) content = content.replace('while 1:', fix) exec(content) while True: ntf = thread.getnotification() if ntf: if ntf == thread.EXIT: return elif ntf == thread.SUSPEND: while thread.wait() != thread.RESUME: pass except Exception as e: print(red(thread.getSelfName() + str(e))) return
def btnA_pressed(): lcd.clear() ## Message m5p_mess = M5StackPrint(FONTPATH, font_size=16, rect=(0, 16 * 2, 320 - 1, 240 - 16 * 2)) global btnAStr s = btnAStr mess = s for j in range(100): s = chr(ord(s) + 1) if s == u'ン': s = u'亜' if s == u'鰐': s = u'あ' mess += s btnAStr = s m5p_mess.print(mess) ## Thread _thread.stack_size(0xB0000) thid = _thread.start_new_thread("THTIME", th_time, ())
def test_stack_size(self): import sys if is_cli or (sys.version_info[0] == 2 and sys.version_info[1] > 4) or sys.version_info[0] > 2: import _thread as thread size = thread.stack_size() self.assertTrue(size == 0 or size >= 32768) bad_size_list = [ 1, -1, -32768, -32769, -32767, -40000, 32767, 32766 ] for bad_size in bad_size_list: self.assertRaises(ValueError, thread.stack_size, bad_size) good_size_list = [4096 * 10, 4096 * 100, 4096 * 1000, 4096 * 10000] for good_size in good_size_list: #CodePlex Work Item 7827 if is_cli and good_size <= 50000: print("Ignoring", good_size, "for CLI") continue temp = thread.stack_size(good_size) self.assertTrue(temp >= 32768 or temp == 0) def temp(): pass thread.start_new_thread(temp, ()) temp = thread.stack_size(1024 * 1024) self.assertTrue(temp >= 32768 or temp == 0)
def main(): '''Main Event Loop''' global interruptCounter, totalInterrupts, CUR_FORMULA, READY, GPIO_ODR, COL_INDEX, COL_TIME # PINS REGISTERS GPIO_REG = const(0x3ff44000) GPIO_EN = const(0x8) GPIO_CLR = const(0xC) BIT21 = const(1 << 21) # 2097152 BIT14 = const(1 << 14) # 16384 BIT26 = const(1 << 26) # 67108864 BIT15 = const(1 << 15) # 32768 BIT25 = const(1 << 25) # 33554432 BIT27 = const(1 << 27) # 134217728 BIT12 = const(1 << 12) # 4096 BIT13 = const(1 << 13) # 8192 LEDS = [BIT21, BIT14, BIT26, BIT15, BIT25, BIT27, BIT12, BIT13] _LED_PINS = [21, 14, 26, 15, 25, 27, 12, 13] LED_PINS = [Pin(i, Pin.OUT, value=0) for i in _LED_PINS] ALL_LEDS = const(237039616) LED_COUNT = const(8) GPIO_ODR = { "REG": GPIO_REG, "EN": GPIO_EN, "CLR": GPIO_CLR, "ALL_LEDS": ALL_LEDS, "LED_COUNT": LED_COUNT } # Last Revolution Time LAST_REV = 0 print("POVPi Ready") display_status(9) # Run Blynk in Thread thread.stack_size(5 * 1024) thread.start_new_thread(run_blynk, ()) # Startup Shadow startup_shadow = {"display": "_LINE_", "enabled": True} update_shadow(new_state=startup_shadow) gc.collect() while 1: # Handle Interrupts if interruptCounter > 0: state = machine.disable_irq() interruptCounter -= 1 machine.enable_irq(state) time_delta = time.ticks_diff(time.ticks_cpu(), LAST_REV) COL_TIME = int(time_delta / 360) COL_INDEX = 0 LAST_REV = time.ticks_cpu() totalInterrupts += 1 if READY and CUR_FORMULA: if LAST_REV == 0: LAST_REV = time.ticks_cpu() if COL_INDEX < 90: byte = CUR_FORMULA[COL_INDEX] COL_INDEX = display(byte, COL_TIME, COL_INDEX, GPIO_REG, GPIO_EN, GPIO_CLR, ALL_LEDS)
def start_mqtt(self): self.mqtt() _thread.stack_size(4 * 1024) self._http_thread = _thread.start_new_thread("MqttSe", self._run_mqtt_process, ())
def _thread_start(func, args, **kwargs): if hasattr(_thread, 'CPU_CORES'): cur = _thread.stack_size() _thread.stack_size(1024*12) ret = _thread.start_new_thread(func, args, cpu_id=_thread.CPU_CORES-1) _thread.stack_size(cur) return ret else: return _thread.start_new_thread(func, args)
def __start_recv_mqtt(self): print_debug(5, "This is PybytesProtocol.__start_recv_mqtt()") self.__pybytes_connection.__connection.set_callback(self.__recv_mqtt) self.__pybytes_connection.__connection.subscribe(self.__mqtt_download_topic) print_debug(2, 'Using {} bytes as stack size'.format(self.__thread_stack_size)) _thread.stack_size(self.__thread_stack_size) _thread.start_new_thread(self.__check_mqtt_message, ()) self.__connectionAlarm = Timer.Alarm(self.__keep_connection, constants.__KEEP_ALIVE_PING_INTERVAL, periodic=True)
def start(): global WebDavState if (network.WLAN(network.STA_IF).isconnected() and WebDavState == False and mongoose.start()): WebDavState = True _thread.stack_size(8 * 1024) _thread.start_new_thread(__poll__, ()) _thread.stack_size() return True return False
def main(): logging.debug("=== MAIN START ===") # Increase stack size per thread this increases micropython recursion depth _thread.stack_size(8192 * 2) # Read and parse configuration from config.json utils.init() controller = MainController() # Check if configuration via access point has to be started if not config.cfg.ap_config_done or wake_reason() == PIN_WAKE: logging.debug("AP_DONE: {}, wake_reason: {}".format( config.cfg.ap_config_done, wake_reason())) logging.debug("SSID: {}, Password: {}".format(config.cfg.ssid, config.cfg.password)) if config.cfg.ssid != 'ssid' and config.cfg.password != 'password': logging.debug("SSID and password aren't default. Try to connect") pass else: logging.debug("=== Entering configuration mode ===") event = MainControllerEvent( MainControllerEventType.CONFIGURE_ACCESS_POINT) controller.add_event(event) logging.debug("Main loop") # If the device is powered on, then actual time from NTP server must be downloaded if reset_cause() == HARD_RESET or reset_cause( ) == PWRON_RESET or reset_cause() == SOFT_RESET: event = MainControllerEvent(MainControllerEventType.TEST_CONNECTION) controller.add_event(event) # Print actual time event = MainControllerEvent(MainControllerEventType.PRINT_TIME) controller.add_event(event) # Read temperature and humidity from the sensor and return the data as JSON event = MainControllerEvent(MainControllerEventType.GET_SENSOR_DATA) controller.add_event(event) # Connect to WIFI and publish JSON with data to AWS via MQTT event = MainControllerEvent(MainControllerEventType.PUBLISH_DATA) controller.add_event(event) # Good night! event = MainControllerEvent(MainControllerEventType.GO_TO_SLEEP, callback=None, ms=config.cfg.data_publishing_period_in_ms) controller.add_event(event) controller.perform()
def start(self, size=2048): self.stop() self.alive = True if Task.lock.acquire(): # print("start") import gc gc.collect() _thread.stack_size(size) _thread.start_new_thread(self.run, ()) _thread.stack_size() Task.lock.release()
def __init__(self, workersCount, workersStackSize=0): if workersStackSize > 0 and workersStackSize < 4096: workersStackSize = 4096 self._workersCount = workersCount self._workersLock = _thread.allocate_lock() self._jobs = [] if workersCount > 0: originalStackSize = _thread.stack_size() _thread.stack_size(workersStackSize) print('Create a pool of %s thread(s) :' % workersCount) for x in range(workersCount): _thread.start_new_thread(self._workerThreadFunc, (None, )) _thread.stack_size(originalStackSize)
def start(topic_head="USER/YANMINGE/MESSAGE", client_id=None, server="mq.makeblock.com", port=1883, user=None, password=None, keepalive=60, ssl=False): global cloud_message_topic cloud_message_client.__init__(client_id, server, port, user, password, keepalive, ssl) _thread.stack_size(CLOUD_MESSAGE_THREAD_STACK_SIZE) _thread.start_new_thread(subscribe_message_received, (), CLOUD_MESSAGE_THREAD_PRIORITY) cloud_message_topic = topic_head cloud_message_client.start_mqtt_check_keepalive()
def neurons_heartbeat_start(): if USE_DICT_CREATED_PRIVIOUSLY: pass else: try: read_general_command_request_to_dict() read_general_command_response_to_dict() read_common_neurons_command_request_to_dict() read_common_neurons_command_response_to_dict() except Exception as e: print("neurons read csv error") print(e) _thread.stack_size(HEART_PACKAGE_THREAD_STACK_SIZE) _thread.start_new_thread(neurons_heartbeat_thread, (), HEART_PACKAGE_THREAD_PRIORITY)
def test_nt_and_posix_stack_size(self): try: thread.stack_size(4096) except ValueError: verbose_print("caught expected ValueError setting " "stack_size(4096)") except thread.error: self.skipTest("platform does not support changing thread stack " "size") fail_msg = "stack_size(%d) failed - should succeed" for tss in (262144, 0x100000, 0): thread.stack_size(tss) self.assertEqual(thread.stack_size(), tss, fail_msg % tss) verbose_print("successfully set stack_size(%d)" % tss) for tss in (262144, 0x100000): verbose_print("trying stack_size = (%d)" % tss) self.next_ident = 0 self.created = 0 with support.wait_threads_exit(): for i in range(NUMTASKS): self.newtask() verbose_print("waiting for all tasks to complete") self.done_mutex.acquire() verbose_print("all tasks done") thread.stack_size(0)
def ffunc(q, *a): _thread.get_ident() _thread._count() _thread.stack_size() local = _thread._local() try: q.empty() q.qsize() ln = rnd.randint(0, 99) for _ in range(ln): rnd.choice([q.put, q.put_nowait])(fitem()) for _ in range(ln): if fbool(): q.get(fbool(), rnd.random()) else: q.get_nowait() except ReferenceError: pass return list(os.urandom(rnd.randint(0, 99)))
def connect_lora_abp(self, lora_timeout, nanogateway): if (self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED): print("Error connect_lora_abp: Connection already exists. Disconnect First") return False try: from network import LoRa except Exception as ex: print("This device does not support LoRa connections: %s" % ex) return False self.lora = LoRa(mode=LoRa.LORAWAN) self.lora.nvram_restore() dev_addr = self.__conf['lora']['abp']['dev_addr'] nwk_swkey = self.__conf['lora']['abp']['nwk_skey'] app_swkey = self.__conf['lora']['abp']['app_skey'] timeout_ms = self.__conf.get('lora_timeout', lora_timeout) * 1000 dev_addr = struct.unpack(">l", binascii.unhexlify(dev_addr.replace(' ', '')))[0] nwk_swkey = binascii.unhexlify(nwk_swkey.replace(' ', '')) app_swkey = binascii.unhexlify(app_swkey.replace(' ', '')) try: print("Trying to join LoRa.ABP for %d seconds..." % lora_timeout) self.lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey), timeout=timeout_ms) # if you want, uncomment this code, but timeout must be 0 # while not self.lora.has_joined(): # print("Joining...") # time.sleep(5) self.__open_lora_socket(nanogateway) _thread.stack_size(self.__thread_stack_size) _thread.start_new_thread(self.__check_lora_messages, ()) return True except Exception as e: message = str(e) if message == 'timed out': print("LoRa connection timeout: %d seconds" % lora_timeout) return False
def _tryStartThread(func, args=()): _ = _thread.stack_size(8 * 1024) for x in range(4): try: gc.collect() th = _thread.start_new_thread("MicroWebServer", func, args) return th except: time.sleep_ms(100) return False
def _tryStartThread(func, args=(), stackSize=4096) : _ = _thread.stack_size(stackSize) for x in range(4) : try : gc.collect() th = _thread.start_new_thread("MicroWebSocket", func, args) return th except : time.sleep_ms(100) return False
def thread_test(): mem() n = 24 # n = 2 # GPy base core dumps at 25 in safe boot mode # , or 21? _thread.stack_size(8 * 1024) # default is 5k print("Starting %d threads...." % (n)) for i in range(n): print('Start thread', i) time.sleep(1) _thread.start_new_thread(th_func, (i + 1, i)) time.sleep(1) mem() time.sleep(1) #achine.info() # mem() if False: keep_going = False
def neurons_heartbeat_start(): if USE_DICT_CREATED_PRIVIOUSLY: pass else: try: read_general_command_request_to_dict() read_general_command_response_to_dict() read_common_neurons_command_request_to_dict() read_common_neurons_command_response_to_dict() except Exception as e: print("read csv file error") if HEART_PACKAGE_USE_INDIVIDUAL_THREAD: _thread.stack_size(HEART_PACKAGE_THREAD_STACK_SIZE) _thread.start_new_thread(neurons_heartbeat_thread, (), HEART_PACKAGE_THREAD_PRIORITY, 2) else: from system.sys_loop import sys_loop_add_operation run_handle = sys_loop_add_operation(neurons_heartbeat_func, (), 0.5) run_handle.run("loop")
def test_stack_size(self): import _thread as thread size = thread.stack_size() self.assertTrue(size == 0 or size >= 32768) bad_size_list = [1, -1, -32768, -32769, -32767, -40000, 32767, 32766] for bad_size in bad_size_list: self.assertRaises(ValueError, thread.stack_size, bad_size) good_size_list = [4096 * 10, 4096 * 100, 4096 * 1000, 4096 * 10000] for good_size in good_size_list: temp = thread.stack_size(good_size) self.assertTrue(temp >= 32768 or temp == 0) def temp(): pass thread.start_new_thread(temp, ()) temp = thread.stack_size(1024 * 1024) self.assertTrue(temp >= 32768 or temp == 0)
def button_control(self, pin=4): ctrl_pin = Pin(pin, Pin.IN, Pin.PULL_UP) self.btn_ctrl = ButtonControl(name="B4", _pin=ctrl_pin, debug=self.debug, on_value=0, off_value=1) self.btn_ctrl.start() _ = _thread.stack_size(5 * 1024) th1 = _thread.start_new_thread("THRD_B_C", self.button_push_check, ())
def main(): print("Run on: %s , B4 pin Control" % client_id) global runner runner = Runner() loop = asyncio.get_event_loop() loop.create_task(runner.main()) _ = _thread.stack_size(7 * 1024) _thread.start_new_thread(loop.run_forever, ())
def test_stack_size(self): import _thread _thread.stack_size(0) res = _thread.stack_size(0) assert res == 0 res = _thread.stack_size(1024 * 1024) assert res == 0 res = _thread.stack_size(2 * 1024 * 1024) assert res == 1024 * 1024 res = _thread.stack_size(0) assert res == 2 * 1024 * 1024
# The Computer Language Benchmarks Game # http://shootout.alioth.debian.org/ # Contributed by Antti Kervinen # Modified by Tupteq # 2to3 import sys import _thread # Set minimum stack size for threads, otherwise the program may fail # to create such a many threads _thread.stack_size(32*1024) def threadfun(number, lock_acquire, next_release): global n while 1: lock_acquire() if n > 0: n -= 1 next_release() else: print(number) main_lock.release() # main n = int(sys.argv[1]) main_lock = _thread.allocate_lock() main_lock.acquire() first_lock = _thread.allocate_lock() next_lock = first_lock
import _thread import traceback import re import queue _thread.stack_size(1024 * 512) # reduce vm size class Input(dict): def __init__(self, conn, raw, prefix, command, params, nick, user, host, mask, paraml, msg): chan = paraml[0].lower() if chan == conn.nick.lower(): # is a PM chan = nick def say(msg): conn.msg(chan, msg) def pm(msg): conn.msg(nick, msg) def reply(msg): if chan == nick: # PMs don't need prefixes conn.msg(chan, msg) else: #conn.msg(chan, '(' + nick + ') ' + msg) try: conn.msg(chan, re.match(r'\.*(\w+.*)',msg).group(1)) except: conn.msg(chan,msg) def me(msg):
def test_stack_size(self): # Various stack size tests. self.assertEquals(_thread.stack_size(), 0, "intial stack size is not 0") _thread.stack_size(0) self.assertEquals(_thread.stack_size(), 0, "stack_size not reset to default") if os.name not in ("nt", "os2", "posix"): return tss_supported = True try: _thread.stack_size(4096) except ValueError: verbose_print("caught expected ValueError setting " "stack_size(4096)") except _thread.error: tss_supported = False verbose_print("platform does not support changing thread stack " "size") if tss_supported: fail_msg = "stack_size(%d) failed - should succeed" for tss in (262144, 0x100000, 0): _thread.stack_size(tss) self.assertEquals(_thread.stack_size(), tss, fail_msg % tss) verbose_print("successfully set stack_size(%d)" % tss) for tss in (262144, 0x100000): verbose_print("trying stack_size = (%d)" % tss) self.next_ident = 0 self.created = 0 for i in range(NUMTASKS): self.newtask() verbose_print("waiting for all tasks to complete") self.done_mutex.acquire() verbose_print("all tasks done") _thread.stack_size(0)
if sys.implementation.name == 'micropython': sz = 2 * 1024 else: sz = 32 * 1024 def foo(): pass def thread_entry(): foo() with lock: global n_finished n_finished += 1 # reset stack size to default _thread.stack_size() # test set/get of stack size print(_thread.stack_size()) print(_thread.stack_size(sz)) print(_thread.stack_size() == sz) print(_thread.stack_size()) lock = _thread.allocate_lock() n_thread = 2 n_finished = 0 # set stack size and spawn a few threads _thread.stack_size(sz) for i in range(n_thread): _thread.start_new_thread(thread_entry, ())
done.release() print ('\n*** Barrier Test ***') if done.acquire(0): raise ValueError("'done' should have remained acquired") bar = barrier(numtasks) running = numtasks for i in range(numtasks): _thread.start_new_thread(task2, (i,)) done.acquire() print ('all tasks done') if hasattr(thread, 'stack_size'): # not all platforms support changing thread stack size print ('\n*** Changing thread stack size ***') if _thread.stack_size() != 0: raise ValueError("initial stack_size not 0") _thread.stack_size(0) if _thread.stack_size() != 0: raise ValueError("stack_size not reset to default") from os import name as os_name if os_name in ("nt", "os2", "posix"): tss_supported = 1 try: _thread.stack_size(4096) except ValueError: print ('caught expected ValueError setting stack_size(4096)') except _thread.error: