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 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 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 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 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 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 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 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 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 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 __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 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 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 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 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 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 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 not is_edge and not is_cef: _set_ie_mode() if sys.getwindowsversion().major >= 6: windll.user32.SetProcessDPIAware() if is_cef: CEF.init(window) app.EnableVisualStyles() app.SetCompatibleTextRenderingDefault(False) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() if not _multiprocessing: thread.Join() else: p = Process() p.join = thread.Join p.is_alive = thread.IsAlive p.name = thread.Name p.kill = thread.Abort return thread else: _main_window_created.wait() i = list(BrowserView.instances.values())[0] # arbitrary instance i.Invoke(Func[Type](create))
def show(self): def start(): if sys.getwindowsversion().major >= 6: windll.user32.SetProcessDPIAware() app = WinForms.Application app.EnableVisualStyles() app.SetCompatibleTextRenderingDefault(False) self.browser = BrowserView.BrowserForm( self.title, self.url, self.width, self.height, self.resizable, self.fullscreen, self.min_size, self.confirm_quit, self.webview_ready) app.Run(self.browser) thread = Thread(ThreadStart(start)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join()
def getChoicesFromList(choiceList=None, prompt=DEFAULT_PROMPT, title=DEFAULT_TITLE, alignChoices=None): """ Ask user to enter their choices from the list and return it. choiceList should be a list of strings """ if alignChoices is None: alignChoices = 'left' choiceData = ChooseFromListModel(choiceList=choiceList, prompt=prompt, title=title, alignChoices=alignChoices) thread = Thread(ThreadStart(lambda: ChooseFromListView(choiceData))) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join() return choiceData.choices
class Watcher(Object): @classmethod def instance(klass): if not hasattr(klass, 'instance_'): klass.instance_ = Watcher() return klass.instance_ def __init__(self): CurrentSession.AddInManager.GetAddIn[DLRIntegrationAddIn]( ).BeforeUnload += self.onBeforeUnload # 普通の #Console にコンテキストを追加する CurrentSession.AddInManager.GetAddIn[ConsoleAddIn]().RegisterContext( DLRContextHelper.Wrap(CurrentSession, "WatcherContext", WatcherContext), "Watcher", "指定したユーザを監視します。") self.config = DLRBasicConfiguration( CurrentSession, "WatcherContext", Dictionary[String, String]({ "Interval": "取得間隔", "Targets": "ウォッチ対象" })) self.targets = filter(lambda x: x != "", (self.config.GetValue("Targets") or "").split(",")) self.interval = int(self.config.GetValue("Interval") or "30", 10) self.running = False self.thread = None self.buffer = {} self.re_source = re.compile(r"<span>from (.*?)</span>") self.re_statuses = re.compile(r"<li class=\"hentry status.*?</li>") self.re_content = re.compile(r"class=\"entry-content\">(.*?)</span>") self.re_user = re.compile( r"class=\"screen-name\" title=\"([^\"]+)\">(.*?)</a>") self.re_user_name = re.compile( r"</span> <span class=\"fn\">(.*?)</span></li>") self.re_user_screen_name = re.compile( r"<meta content=\"([^\"]+)\" name=\"page-user-screen_name\" />") self.re_anchor = re.compile( r"<a href=\"(http://[^\"]*)\"[^>]*>.*?</a>") self.re_tag = re.compile(r"<[^>]*>") self.re_status_id = re.compile(r"id=\"status_(\d+)\"") def start(self): if not self.running: CurrentSession.TwitterService.CookieLogin() self.thread = Thread(ThreadStart(self.runProc)) self.thread.Start() def runProc(self): Trace.WriteLine("Start Watching") self.running = True while self.interval > 0 and len(self.targets) > 0: for target in self.targets: try: self.fetch(target) except: Trace.WriteLine(sys.exc_info().ToString()) Thread.Sleep(self.interval * 1000) self.running = False Trace.WriteLine("Stop Watching") def fetch(self, screenName): home = CurrentSession.TwitterService.GETWithCookie( ("/%s" % screenName)) statuses = self.re_statuses.findall(home) statuses.reverse() # User m_name = self.re_user_name.search(home) m_screen_name = self.re_user_screen_name.search(home) user = User() user.Id = 0 user.Name = m_name.group(1) user.ScreenName = m_screen_name.group(1) if not self.buffer.has_key(user.ScreenName): self.buffer[user.ScreenName] = [] for status in statuses: s = Status() # Status s.User = user s.Source = self.re_source.search(status).group(1) s.Text = Utility.UnescapeCharReference( self.re_tag.sub( r"", self.re_anchor.sub( r"\1", self.re_content.search(status).group(1)))) s.Id = int(self.re_status_id.search(status).group(1), 10) s.CreatedAt = DateTime.Now #Trace.WriteLine(s.ToString()) #Trace.WriteLine(repr(self.buffer[user.ScreenName])) # 流れていないものだけ流す if not s.Id in self.buffer[user.ScreenName]: self.buffer[user.ScreenName].append(s.Id) CurrentSession.TwitterService.ProcessStatus( s, Action[Status](lambda s1: CurrentSession. ProcessTimelineStatus(s1, False, False))) if len(self.buffer[user.ScreenName]) > 50: self.buffer[user.ScreenName].pop(0) def onBeforeUnload(self, sender, e): CurrentSession.AddInManager.GetAddIn[ConsoleAddIn]().UnregisterContext( DLRContextHelper.Wrap(CurrentSession, "WatcherContext", WatcherContext)) self.interval = 0 self.thread.Abort() self.thread.Join(5000)
def main(): thread = Thread(ThreadStart(app_thread)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join()
('raiseAnchor', 'Raise Anchor'), ('dropAnchor', 'Drop Anchor'), ('turnLeft', 'Turn Left'), ('turnRight', 'Turn Right'), ('start', 'Start')] self.setEvents() def setEvents(self): for x in self.events: btn = self.Content.FindName(x[0]) btn.Click += self.clickButton def clickButton(self, sender, event): for x in self.events: if x[0] == event.Source.Name: Msg(x[1]) def ShowWindow(): try: c = XamlWindow() c.ShowDialog() except Exception as e: # if you don't catch these, an exception will likely take down CUO/CA print e t = Thread(ThreadStart(ShowWindow)) t.SetApartmentState(ApartmentState.STA) t.Start() t.Join()