def testUnmanagedThreadState(self, mapper, _): mapper.ReleaseGIL() # current thread state should be null if nobody has the GIL self.assertEquals(CPyMarshal.ReadPtr(mapper._PyThreadState_Current), IntPtr.Zero) mapper.EnsureGIL() mapper.LastException = NameError("Harold") ts = CPyMarshal.ReadPtr(mapper._PyThreadState_Current) curexc_type = CPyMarshal.ReadPtrField(ts, PyThreadState, "curexc_type") curexc_value = CPyMarshal.ReadPtrField(ts, PyThreadState, "curexc_value") self.assertEquals(mapper.Retrieve(curexc_type), NameError) self.assertEquals(mapper.Retrieve(curexc_value), "Harold") mapper.ReleaseGIL() def CheckOtherThread(): mapper.EnsureGIL() ts2 = CPyMarshal.ReadPtr(mapper._PyThreadState_Current) self.assertNotEquals(ts2, ts) curexc_type = CPyMarshal.ReadPtrField(ts2, PyThreadState, "curexc_type") curexc_value = CPyMarshal.ReadPtrField(ts2, PyThreadState, "curexc_value") self.assertEquals(curexc_type, IntPtr.Zero) self.assertEquals(curexc_value, IntPtr.Zero) mapper.ReleaseGIL() thread = Thread(ThreadStart(CheckOtherThread)) thread.Start() thread.Join() mapper.EnsureGIL()
def SetText(text): def thread_proc(): System.Windows.Forms.Clipboard.SetText(text) t = Thread(ThreadStart(thread_proc)) t.ApartmentState = System.Threading.ApartmentState.STA t.Start()
def testRun(): autoResetEvent = AutoResetEvent(False) data = {} if hasattr(clr, "SetCommandDispatcher"): # for IP 2.x def setCommandDispatcher(cmd): clr.SetCommandDispatcher(cmd) else: # for IP 1.x def setCommandDispatcher(cmd): IronPython.Hosting.PythonEngine.ConsoleCommandDispatcher = cmd def threadProc(): try: dispatcher = Form(Size=Size(0,0)) dispatcher.Show() # create a dummy control (for invoking commands from) dispatcher.Hide() # and show & hide to initialise it. data["dispatcher"] = dispatcher autoResetEvent.Set() # indicate that we are ready Application.Run() # start the message loop finally: setCommandDispatcher(None) def dispatchConsoleCommand(consoleCommand): dispatcher = data.get("dispatcher") if consoleCommand: dispatcher.Invoke(consoleCommand) else: Application.Exit() t = Thread(ThreadStart(threadProc)) t.IsBackground = True t.Start() autoResetEvent.WaitOne() # Wait until the alt input execution setCommandDispatcher(dispatchConsoleCommand)
def runTest(): global writerAlive global readerAlive writerAlive = True readerAlive = True a = Thread(ThreadStart(reader)) a.IsBackground = True a.Start() if isinstance(writerWorker, tuple): b = [] index = 0 for wr in writerWorker: th = Thread(ThreadStart(writer(wr, index))) th.IsBackground = True th.Start() b.append(th) index = index + 1 else: b = [Thread(ThreadStart(writer(writerWorker, 0)))] b[0].IsBackground = True b[0].Start() go.Set() a.Join() for th in b: th.Join()
def create_window(window): def create(): browser = BrowserView.BrowserForm(window) BrowserView.instances[window.uid] = browser if not window.hidden: browser.Show() _main_window_created.set() if window.uid == "master": app.Run() app = WinForms.Application if window.uid == "master": if sys.getwindowsversion().major >= 6: windll.user32.SetProcessDPIAware() CEF.init(window) app.EnableVisualStyles() app.SetCompatibleTextRenderingDefault(False) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join() else: _main_window_created.wait() i = list(BrowserView.instances.values())[0] # arbitrary instance i.Invoke(Func[Type](create))
def __start_thread_loop(self): ''' Starts (and returns) the background thread, which will wait-loop forever, running tasks that are submitted via the 'submit' method, until it is flagged by the 'shutdown' method to terminate. ''' def threadloop(): task = None while task != self: try: Monitor.Enter(self) try: task = self.task if task != self: self.task = None if task is None: Monitor.Wait(self) finally: Monitor.Exit(self) if task != self and task is not None: task() except Exception as ex: # slightly odd error handling, cause this thread should NEVER # die as the result of an exception! try: log.handle_error(ex) except: pass task = None thread = Thread(ThreadStart(threadloop)) thread.IsBackground = True thread.Start() return thread
def main(): """Prints information about the guessing session and starts the multithreading.""" word_banner = '{} version: {}. Coded by: {}'.format( sys.argv[0], __version__, __author__) print('=' * len(word_banner)) print(word_banner) print('=' * len(word_banner)) print for arg in vars(args): if getattr(args, arg): print('{}: {}'.format( arg.title().replace('_',' '), getattr(args, arg))) print print ('[*] Guessing {} user(s) and {} password(s). {} total' ' guesses.'.format( len(usernames), len(passwords), len(usernames) * len(passwords) )) print '[*] Only printing valid username/password combinations.\n' for i in range(args.threads): t = Thread(ThreadStart(manage_queue)) t.Start() for current_user in usernames: user_queue.Enqueue(current_user)
def mesh2ps(topo): vp = topo.VertexPositions ptslist = [[vp[i.A], vp[i.B], vp[i.C]] for i in topo.FaceIndices] len1 = len(ptslist) / NUMTHREADS + 1 if len(ptslist) > NUMTHREADS * 3 and NUMTHREADS > 1: ptslist = chop(ptslist, len1) class Worker(object): __slots__ = 'fn', 'args', 'result' def __init__(self, fn, args): self.fn = fn self.args = args self.result = None def __call__(self): self.result = self.fn(*self.args) workers, tasks = [], [] for p in ptslist: w = Worker(ps_generator, (p, )) t = Thread(ThreadStart(w)) workers.append(w) tasks.append(t) t.Start() for t in tasks: t.Join() return PolySurface.ByJoinedSurfaces(i for w in workers for i in w.result) else: return PolySurface.ByJoinedSurfaces(ps_generator(ptslist))
def create_window(uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready): def create(): window = BrowserView.BrowserForm(uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready) BrowserView.instances[uid] = window window.Show() if uid == 'master': app.Run() webview_ready.clear() app = WinForms.Application if uid == 'master': set_ie_mode() if sys.getwindowsversion().major >= 6: windll.user32.SetProcessDPIAware() app.EnableVisualStyles() app.SetCompatibleTextRenderingDefault(False) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join() else: i = list(BrowserView.instances.values())[0] # arbitrary instance i.Invoke(Func[Type](create))
def InitializeErrorWatcher(self): from System.Threading import Thread, ThreadStart import thread self.errorLock = thread.allocate_lock() self.errorString = "" th = Thread(ThreadStart(self.WatchErrorStream)) th.IsBackground = True th.Start()
def run_many(nthreads, ntimes, nbits): lst_threads = [] for i in range(nthreads): t = Thread(ParameterizedThreadStart(foo)) t.Start((ntimes, nbits)) lst_threads.append(t) for t in lst_threads: t.Join()
def GetText(): def thread_proc(): global clipboardcontents clipboardcontents = System.Windows.Forms.Clipboard.GetText() t = Thread(ThreadStart(thread_proc)) t.ApartmentState = System.Threading.ApartmentState.STA t.Start() t.Join()
def create_window(config): def create(): Application().Run(MacronWindow(config)) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join()
def execute(self, runnable): runner = Runner(runnable) thread = Thread(ThreadStart(runner)) thread.IsBackground = True thread.Start() if not thread.Join(self._timeout * 1000): thread.Abort() raise self._error return runner.get_result()
def run_debugger(py_file): if Thread.CurrentThread.GetApartmentState() == ApartmentState.STA: t = Thread(ParameterizedThreadStart(run_debugger)) t.SetApartmentState(ApartmentState.MTA) t.Start(py_file) t.Join() else: p = IPyDebugProcess() p.run(py_file)
def run(cls, xaml=None): '''调用 run 函数启动窗口程序 :param xaml: xaml 文件路径或者 xaml 格式的 xml 字符串 ''' thread = Thread(ParameterizedThreadStart(cls._thread)) thread.SetApartmentState(ApartmentState.STA) thread.Start(xaml) thread.Join()
def startInteractive(): global are are = AutoResetEvent(False) t = Thread(ThreadStart(appStart)) t.ApartmentState = ApartmentState.STA t.Start() are.WaitOne() IronPython.Hosting.PythonEngine.ConsoleCommandDispatcher = DispatchConsoleCommand
def __init__(self, API_key=''): def start(): self.browser = AuthDialog.FormBrowser(API_key) WinForms.Application.Run(self.browser) # Create a new thread to run the process thread = Thread(ThreadStart(start)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join()
def open_tkinter_dialog(title, initial_folder): out_queue = Queue() out_queue.Enqueue(title) out_queue.Enqueue(initial_folder) start = ParameterizedThreadStart(tkinter_dialog_thread) thread = Thread(start) thread.SetApartmentState(ApartmentState.STA) thread.Start(out_queue) thread.Join() final_result = out_queue.Dequeue() return final_result[0], final_result[1]
def __init__(self): self.last_input = None; self.__input_update_thread = Thread(ThreadStart(self.__update_input)); self.__input_update_thread.Start() os.system("cls") # os.system("clear") Console.Title = "Snake by LuYU426" # The next line needed to be commented out on Unix-like systems. However before running, the console needs to be adjusted accordingly Console.CursorVisible = False; Console.WindowWidth = 80; Console.WindowHeight = 25;Console.BufferHeight = Console.WindowHeight; Console.BufferWidth = Console.WindowWidth for i in range(0,24): for j in range(0, 80): if i == 0 or j == 0: self.__show(j, i, Screen.black, "#") elif i == 22 or j == 79: self.__show(j, i, Screen.black,"#") else: self.__show(j, i, Screen.black," ")
def execute(self, contents): self.printer.print_lines(contents) self.Text = '' self.history.append(contents) self._sync.Reset() started = ManualResetEvent(False) if self._temp_context is not None: self.context.update(self._temp_context) def _execute(): context = self.context started.Set() try: code = compile(contents + '\n', '<stdin>', 'single', PyCF_DONT_IMPLY_DEDENT) exec code in context except: if reset_event.WaitOne(1): # don't print exception messages if thread has been terminated return exc_type, value, tb = sys.exc_info() if value is None: # String exceptions # workaround for IronPython bug exc_type = Exception value = Exception('StringException') tblist = traceback.extract_tb(tb) message = traceback.format_list(tblist) del message[:1] if message: # we don't print the 'Traceback...' part for SyntaxError message.insert(0, "Traceback (most recent call last):\n") message.extend(traceback.format_exception_only( exc_type, value)) self.printer.print_new(''.join(message)) # access through closure not on self as we may be an orphaned # thread - with a new reset_event on self result = reset_event.WaitOne(0) if not reset_event.WaitOne(0): self.completed() self._sync.Set() self._thread_reset = reset_event = ManualResetEvent(False) self._thread = Thread(ThreadStart(_execute)) self._thread.IsBackground = True self._thread.Name = "executing" self._thread.Start() self.prompt.Visibility = Visibility.Collapsed if hasattr(self, 'CaretBrush'): self.CaretBrush = self._disabled started.WaitOne()
def test_thread(self): from System.Threading import ParameterizedThreadStart, Thread, ThreadStart class Sync: hit = 0 def ThreadProcParm(parm): parm.hit = 1 def ThreadProcNoParm(): pass def Main(): sync = Sync() t = Thread(ParameterizedThreadStart(ThreadProcParm)) t.Start(sync) t.Join() self.assertTrue(sync.hit == 1) t = Thread(ThreadStart(ThreadProcNoParm)) t.Start() t.Join() Main() def import_sys(): import sys self.assertTrue(sys != None) t = Thread(ThreadStart(import_sys)) t.Start() t.Join() so = sys.stdout se = sys.stderr class myStdOut: def write(self, text): pass sys.stdout = myStdOut() sys.stderr = myStdOut() import thread def raises(*p): raise Exception id = thread.start_new_thread(raises, ()) Thread.Sleep(1000) # wait a bit and make sure we don't get ripped. sys.stdout = so sys.stderr = se
def show(self): def start(): self.browser = BrowserView.BrowserForm( self.title, self.url, self.width, self.height, self.resizable, self.fullscreen, self.min_size, self.webview_ready) app = WinForms.Application app.Run(self.browser) thread = Thread(ThreadStart(start)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join()
def EnableDrop(): def thread_proc(): form = DragDrop(IN[2]) form.add_range(l1_arr) Application.Run(form) global out1 out1 = form.output1 Application.Exit() t1 = Thread(ThreadStart(thread_proc)) t1.ApartmentState = System.Threading.ApartmentState.STA t1.Start() t1.Join()
def testLastExceptionIsThreadLocal(self, mapper, _): def CheckOtherThread(): self.assertEquals(mapper.LastException, None) mapper.LastException = ValueError('foo') self.assertEquals(isinstance(mapper.LastException, ValueError), True) mapper.LastException = TypeError('bar') thread = Thread(ThreadStart(CheckOtherThread)) thread.Start() thread.Join() self.assertEquals(isinstance(mapper.LastException, TypeError), True)
def wait_until_ready(): ''' Waits until a fixed amount of time has passed since this function was last called. Returns immediately if that much time has already passed. ''' global __next_query_time_ms, __QUERY_DELAY_MS time_ms = (DateTime.Now-DateTime(1970,1,1)).TotalMilliseconds wait_ms = __next_query_time_ms - time_ms if wait_ms > 0: t = Thread(ThreadStart(lambda x=0: Thread.CurrentThread.Sleep(wait_ms))) t.Start() t.Join() time_ms = (DateTime.Now-DateTime(1970,1,1)).TotalMilliseconds __next_query_time_ms = time_ms + __QUERY_DELAY_MS
class NotifyFlowVelocity(Object): @classmethod def instance(klass): if not hasattr(klass, 'instance_'): klass.instance_ = NotifyFlowVelocity() return klass.instance_ def __init__(self): # 普通の #Console にコンテキストを追加する CurrentSession.AddInManager.GetAddIn[DLRIntegrationAddIn]( ).BeforeUnload += self.onBeforeUnload CurrentSession.PostProcessTimelineStatuses += self.onPostProcessTimelineStatuses self.running = False self.thread = None self.total_status_count = 0 self.status_count = 0 self.notify_count = 1 def start(self): if not self.running: self.thread = Thread(ThreadStart(self.runProc)) self.thread.Start() def runProc(self): self.running = True while 1: Thread.Sleep(60 * 60 * 1000) try: self.notify() except: Trace.WriteLine(sys.exc_info().ToString()) self.running = False def notify(self): self.total_status_count += self.status_count CurrentSession.SendTwitterGatewayServerMessage( "Twitterの流速は 現在: %d, 平均: %d です。" % (self.status_count, self.total_status_count / self.notify_count)) self.status_count = 0 self.notify_count += 1 def onPostProcessTimelineStatuses(self, sender, e): if not e.IsFirstTime: self.status_count += len(e.Statuses.Status) def onBeforeUnload(self, sender, e): CurrentSession.PostProcessTimelineStatuses -= self.onPostProcessTimelineStatuses self.thread.Abort() self.thread.Join(5000)
def main(): port = 8014 print 'starting server on port: %d' % port revitEventHandler = RevitToCitySimEventHandler() externalEvent = ExternalEvent.Create(revitEventHandler) server = SnapshotServer(port, externalEvent, revitEventHandler.contexts) serverThread = Thread(ThreadStart(server.serve_forever)) serverThread.Start() print 'started server thread' def closing(s, a): server.stop() return __window__.FormClosing += closing # NOQA
def show(self): def start(): app = WinForms.Application self.browser = BrowserView.BrowserForm( self.title, self.url, self.width, self.height, self.resizable, self.fullscreen, self.min_size, self.confirm_quit, self.background_color, self.debug, self.js_api, self.webview_ready) app.Run(self.browser) thread = Thread(ThreadStart(start)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join()
def mesh2ps(topo, f_chop=chop1, itemgetter=itemgetter, f_ps1=PolySurface.ByJoinedSurfaces, f_sf1=Surface.ByPerimeterPoints): NUMTHREADS = 4 vp = topo.VertexPositions ptslist = [itemgetter(i.A, i.B, i.C)(vp) for i in topo.FaceIndices] len1 = len(ptslist) / NUMTHREADS + 1 def ps_generator(ptslist, chop1=chop1, f_ps1=PolySurface.ByJoinedSurfaces, f_sf1=Surface.ByPerimeterPoints): sflist = map(f_sf1, ptslist) while len(sflist) > 10: sflist = map(f_ps1, chop1(sflist, 10)) return sflist if len(ptslist) > 10: ptslist = f_chop(ptslist, len1) class Worker(object): __slots__ = 'fn', 'args', 'result' def __init__(self, fn, args): self.fn = fn self.args = args self.result = None def __call__(self): self.result = self.fn(*self.args) workers, tasks = [], [] for p in ptslist: w = Worker(ps_generator, (p, )) t = Thread(ThreadStart(w)) workers.append(w) tasks.append(t) t.Start() for t in tasks: t.Join() return f_ps1(i for w in workers for i in w.result) else: return f_ps1(ps_generator(ptslist))
def run_job(self, job, requests): job = self.decode_job(job) payload = {'id': job['id']} if DEBUG: print "Running job (id: {})".format(job['id']) try: result = getattr(self, job['command'])(job['data']) payload['state'] = 'success' payload['result'] = result except AttributeError as e: #traceback.print_exc() payload['state'] = 'error' payload['result'] = 'Unknown command {}'.format(job['command'], e) except Exception as e: #traceback.print_exc() payload['state'] = 'error' payload[ 'result'] = 'Exception when executing command {}: {}'.format( job['command'], e) payload = self.encode_job(payload) while True: try: requests.post(urljoin(self.URL, '/jobs', job['id']), json=payload) return except Exception as e: if DEBUG: print "Error sending job results (id: {}): {}".format( job['id'], e) Thread.Sleep(self.SLEEP)
def test_thread_local(self): import thread from System.Threading import Thread x = thread._local() #--Sanity x.foo = 42 self.assertEqual(x.foo, 42) global found found = None def f(): global found found = hasattr(x, 'foo') thread.start_new_thread(f, ()) while found == None: Thread.Sleep(100) self.assertTrue(not found) self.assertEqual(x.__dict__, {'foo': 42}) try: x.__dict__ = None self.fail("Should not be able to set thread._local().__dict__!") except AttributeError, e: pass
def Main(): sync = Sync() t = Thread(ParameterizedThreadStart(ThreadProcParm)) t.Start(sync) t.Join() self.assertTrue(sync.hit == 1) t = Thread(ThreadStart(ThreadProcNoParm)) t.Start() t.Join()
def start(self): log.debug("starting new thread") t = Thread(ThreadStart(self.target)) t.IsBackground = True t.Start()
dispatcher = Form(Size=Size(0, 0)) dispatcher.Show() dispatcher.Hide() # Signal that the thread running thread_proc is ready for the main # thread to send input to it. are.Set() # Start the message loop. Application.Run() finally: # In case thread_proc's thread dies, restore the default IronPython # console execution behavior. clr.SetCommandDispatcher(None) def DispatchConsoleCommand(consoleCommand): if consoleCommand: # consoleCommand is a delegate for a dynamic method that embodies the # input expression from the user. Run it on the other thread. dispatcher.Invoke(consoleCommand) else: Application.Exit() t = Thread(ThreadStart(thread_proc)) t.IsBackground = True t.Start() # Don't establish the alternative input execution behavior until the other # thread is ready. Note, 'are' starts out unsignalled. are.WaitOne() clr.SetCommandDispatcher(DispatchConsoleCommand)