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 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 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 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(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 test_error_message(self): def func(a, b, c, d, e): pass from System.Threading import ThreadStart ts = ThreadStart(func) self.assertRaises(TypeError, ts)
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 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 __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 test_handler_get_invoked(self): import IronPythonTest from System.Threading import ParameterizedThreadStart, ThreadStart def myfunc(): global myfuncCalled myfuncCalled = True def myotherfunc(arg): global myfuncCalled, passedarg myfuncCalled = True passedarg = arg class myclass(object): def myfunc(self): global myfuncCalled myfuncCalled = True def myotherfunc(self, arg): global myfuncCalled,passedarg myfuncCalled = True passedarg = arg class myoldclass: def myfunc(self): global myfuncCalled myfuncCalled = True def myotherfunc(self, arg): global myfuncCalled, passedarg myfuncCalled = True passedarg = arg global myfuncCalled, passedarg for target in [myfunc, myclass().myfunc, myoldclass().myfunc]: myfuncCalled = False ThreadStart(target)() self.assertEqual(myfuncCalled, True) for target in [myotherfunc, myclass().myotherfunc, myoldclass().myotherfunc]: myfuncCalled = False passedarg = None ParameterizedThreadStart(target)(1) self.assertEqual(myfuncCalled, True) self.assertEqual(passedarg, 1) # verify we can call a delegate that's bound to a static method IronPythonTest.DelegateTest.Simple() # Untyped delegate. System.Windows.Forms.Control.Invoke(Delegate) is an example of such an API self.assertRaises(TypeError, IronPythonTest.DelegateTest.InvokeUntypedDelegate, myfunc) myfuncCalled = False IronPythonTest.DelegateTest.InvokeUntypedDelegate(IronPythonTest.SimpleDelegate(myfunc)) self.assertEqual(myfuncCalled, True) myfuncCalled = False passedarg = 0 IronPythonTest.DelegateTest.InvokeUntypedDelegate(IronPythonTest.SimpleDelegateWithOneArg(myotherfunc), 100) self.assertEqual((myfuncCalled, passedarg), (True, 100))
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 create_window(config): def create(): Application().Run(MacronWindow(config)) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.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 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 __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 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 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 startInteractive(): global are are = AutoResetEvent(False) t = Thread(ThreadStart(appStart)) t.ApartmentState = ApartmentState.STA t.Start() are.WaitOne() IronPython.Hosting.PythonEngine.ConsoleCommandDispatcher = DispatchConsoleCommand
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 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 __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 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 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 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
def show_threadsafe(cls, *args): ''' A threadsafe method for instantiating a new ComicForm on a NEW Application thread, and then displaying it to the user. The Application thread will shutdown and dispose automatically when the ComicForm is closed. All given arguments will be passed to the new ComicForm's constructor. ''' cls.newform = None def shower(): with cls(*args) as form: Monitor.Enter(cls) try: cls.newform = form Monitor.Pulse(cls) finally: Monitor.Exit(cls) def exception_handler(sender, event): log.handle_error(event.Exception) Application.ThreadException +=\ ThreadExceptionEventHandler(exception_handler) Application.Run(form) # start form on new App thread; blocks Monitor.Enter(cls) try: # starts a new thread, which will become the Application thread/ event # pump for the newly created ComicForm, Thread(ThreadStart(shower)).Start() Monitor.Wait(cls) finally: Monitor.Exit(cls) newform = cls.newform del cls.newform # make sure this method does not return until the newly created ComicForm # has actually been made visible and active. see bug 139. def activate_form(): # this call is probably not needed; the real trick here is that # invoking this method synchronously delays us until the form has # a nice, visible handle on-screen newform.Activate() utils.invoke(newform, activate_form, True) return newform
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