def testAcquireAndReleaseLocksWithWait(self, mapper, _): lockPtr1 = mapper.PyThread_allocate_lock() lockPtr2 = mapper.PyThread_allocate_lock() self.assertEquals(mapper.PyThread_acquire_lock(lockPtr1, 1), 1, "claimed failure") self.assertEquals(mapper.PyThread_acquire_lock(lockPtr2, 1), 1, "claimed failure") acquired = set() def AcquireLock(ptr): self.assertEquals(mapper.PyThread_acquire_lock(ptr, 1), 1, "claimed failure") acquired.add(ptr) mapper.PyThread_release_lock(ptr) t1 = Thread(ThreadStart(lambda: AcquireLock(lockPtr1))) t2 = Thread(ThreadStart(lambda: AcquireLock(lockPtr2))) t1.Start() t2.Start() Thread.CurrentThread.Join(100) self.assertEquals(acquired, set(), "not properly locked") mapper.PyThread_release_lock(lockPtr1) Thread.CurrentThread.Join(100) self.assertEquals(acquired, set([lockPtr1]), "release failed") mapper.PyThread_release_lock(lockPtr2) Thread.CurrentThread.Join(100) self.assertEquals(acquired, set([lockPtr1, lockPtr2]), "release failed")
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 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 test_identity(self): import IronPythonTest from System.Threading import ParameterizedThreadStart, Thread, ThreadStart global called global globalSelf def identity(x): return x r = IronPythonTest.ReturnTypes() r.floatEvent += identity import System self.assertEqual(r.RunFloat(1.4), System.Single(1.4)) # try parameterized thread a = foo() t = Thread(ParameterizedThreadStart(foo.bar)) t.Start(a) t.Join() self.assertEqual(called, True) self.assertEqual(globalSelf, a) # try non-parameterized a = foo() called = False t = Thread(ThreadStart(a.bar)) t.Start() t.Join() self.assertEqual(called, True) self.assertEqual(globalSelf, a) # parameterized w/ self a = foo() called = False t = Thread(ParameterizedThreadStart(a.baz)) t.Start('hello') t.Join() self.assertEqual(called, True) self.assertEqual(globalSelf, a) self.assertEqual(globalArg, 'hello') # parameterized w/ self & extra arg, should throw try: pts = ParameterizedThreadStart(foo.baz) pts("Hello") self.assertUnreachable() except TypeError: pass
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 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(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 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 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 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 __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 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 create_window(config): def create(): Application().Run(MacronWindow(config)) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join()
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_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 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 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 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 testAcquireAndReleaseLocksWithNoWait(self, mapper, _): lockPtr1 = mapper.PyThread_allocate_lock() lockPtr2 = mapper.PyThread_allocate_lock() self.assertEquals(mapper.PyThread_acquire_lock(lockPtr1, 1), 1, "claimed failure") self.assertEquals(mapper.PyThread_acquire_lock(lockPtr2, 1), 1, "claimed failure") failedToAcquire = set() def FailToAcquireLock(ptr): self.assertEquals(mapper.PyThread_acquire_lock(ptr, 0), 0, "claimed success") failedToAcquire.add(ptr) t1 = Thread(ThreadStart(lambda: FailToAcquireLock(lockPtr1))) t2 = Thread(ThreadStart(lambda: FailToAcquireLock(lockPtr2))) t1.Start() t2.Start() Thread.CurrentThread.Join(100) self.assertEquals(failedToAcquire, set([lockPtr1, lockPtr2]), "failed") mapper.PyThread_release_lock(lockPtr1) mapper.PyThread_release_lock(lockPtr2) acquired = set() def AcquireLock(ptr): self.assertEquals(mapper.PyThread_acquire_lock(ptr, 0), 1, "claimed failure") acquired.add(ptr) mapper.PyThread_release_lock(ptr) t1 = Thread(ThreadStart(lambda: AcquireLock(lockPtr1))) t2 = Thread(ThreadStart(lambda: AcquireLock(lockPtr2))) t1.Start() t2.Start() Thread.CurrentThread.Join(100) self.assertEquals(acquired, set([lockPtr1, lockPtr2]), "acquires failed")
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 testMultiThreaded(self): lock = Lock() def TestCanAcquire(): self.assertEquals(lock.Acquire(), 1) self.assertEquals(lock.IsAcquired, True) lock.Release() t = Thread(ThreadStart(TestCanAcquire)) t.Start() t.Join() lock.Acquire() def TestCannotAcquire(): self.assertEquals(lock.TryAcquire(), False) self.assertEquals(lock.IsAcquired, False) t = Thread(ThreadStart(TestCannotAcquire)) t.Start() t.Join() lock.Release()
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