def __Connect2Client(self, number): self.__connectionLock.acquire(); self.__neighborLock.acquire(); Neighborhood = lminus(self.__ClientNeighborhood, self.__ClientConnectionIPs) potentialconnect = sample(Neighborhood, min(len(Neighborhood),number)) for eachClient in potentialconnect: if self.__NumofConnections < self.__MaxNumConn: if eachClient not in self.__ClientConnectionIPs: cliSock = Mytcpsocket() ack1 = cliSock.Connect2Server(eachClient) ack2 = cliSock.sendmsg(self.__Addr[1]) ack3 = cliSock.recvmsg(BUFSIZ) # receive ACK if ack1 and ack2 and ack3!='closed': self.__NumofConnections += 1 self.__ClientConnectionSocks.append(cliSock); self.__ClientConnectionIPs.append(eachClient); t = MyThread(self.__upload,(cliSock,eachClient),self.__upload.__name__) self.__UploadThreadsLock.acquire(); self.__UploadThreads.append(t); self.__UploadThreadsLock.release() self.__BWControlBoot.set(); # start BW control self.__RateAllocBoot.set(); # start rate allocation t.start(); sleep(PROCESS_TIME); else: self.__ClientNeighborhood.remove(eachClient) else: break; self.__connectionLock.release(); self.__neighborLock.release();
def __WaitforConnection(self, *targs): self.__tcpListenSock.InitServSock(self.__Addr, self.__MaxNumConn) while True: if self.__EXIT: return (tcpServSock, SERVER_ADDR) = self.__tcpListenSock.WaitforConn() self.__connectionLock.acquire() servtcpsock = Mytcpsocket(tcpServSock) if self.__NumofConnections < self.__MaxNumConn: servport = servtcpsock.recvmsg(BUFSIZ) ack = servtcpsock.sendmsg('ACK') # send ACK SERVER_SERV_ADDR = (SERVER_ADDR[0], servport) if ((SERVER_SERV_ADDR in self.__ServerConnectionIPs) or (SERVER_SERV_ADDR == self.__ExcludedServerAddr) or (not ack) or servport == 'closed'): servtcpsock.close() else: self.__ServerConnectionSocks.append(servtcpsock) self.__ServerConnectionIPs.append(SERVER_SERV_ADDR) self.__NumofConnections += 1 if VERBOSE: print "...connected from:", SERVER_SERV_ADDR t = MyThread( self.__download, (servtcpsock, SERVER_SERV_ADDR, self.__currentvid), self.__download.__name__) t.start() sleep(PROCESS_TIME) self.__downloadthreads.append(t) else: servtcpsock.close( ) # close if the number of connections exceeds max self.__connectionLock.release()
def __Connect2Server(self, *targs): args = targs[0] number = args[0] videohash = args[1] self.__connectionLock.acquire() self.__neighborLock.acquire() Neighborhood = lminus(self.__ServerNeighborhood, self.__ServerConnectionIPs) potentialconnect = sample(Neighborhood, min(len(Neighborhood), number)) for eachServer in potentialconnect: if self.__NumofConnections < self.__MaxNumConn: if eachServer not in self.__ServerConnectionIPs: servSock = Mytcpsocket() ack1 = servSock.Connect2Server(eachServer) ack2 = servSock.sendmsg(self.__Addr[1]) ack3 = servSock.recvmsg(BUFSIZ) # receive ACK if ack1 and ack2 and ack3 != 'closed': self.__NumofConnections += 1 self.__ServerConnectionSocks.append(servSock) self.__ServerConnectionIPs.append(eachServer) t = MyThread(self.__download, (servSock, eachServer, videohash), self.__download.__name__) t.start() sleep(PROCESS_TIME) self.__downloadthreads.append(t) else: self.__ServerNeighborhood.remove(eachServer) else: break self.__connectionLock.release() self.__neighborLock.release()
def __WaitforConnection(self, *targs): self.__tcpSerSock.InitServSock(self.__Addr,self.__MaxNumConn) if VERBOSE: print "Waiting for connection..." while True: (tcpClientSock, CLIENT_ADDR) = self.__tcpSerSock.WaitforConn() self.__connectionLock.acquire(); clitcpsock = Mytcpsocket(tcpClientSock) if self.__NumofConnections < self.__MaxNumConn: servport = clitcpsock.recvmsg(BUFSIZ) ack = clitcpsock.sendmsg('ACK') CLIENT_SERV_ADDR = (CLIENT_ADDR[0],servport) if ((CLIENT_SERV_ADDR in self.__ClientConnectionIPs) or (not ack) or servport == 'closed'): clitcpsock.close() else: self.__ClientConnectionSocks.append(clitcpsock); self.__ClientConnectionIPs.append(CLIENT_SERV_ADDR); self.__NumofConnections += 1; if VERBOSE: print "...connected from:", CLIENT_ADDR t = MyThread(self.__upload,(clitcpsock,CLIENT_SERV_ADDR),self.__upload.__name__) self.__UploadThreadsLock.acquire(); self.__UploadThreads.append(t); self.__UploadThreadsLock.release() self.__BWControlBoot.set(); # start BW control self.__RateAllocBoot.set(); # start rate allocation t.start(); sleep(PROCESS_TIME); else: clitcpsock.close() # close if the number of connections exceeds max self.__connectionLock.release();
def __Connect2Client(self, number): self.__connectionLock.acquire() self.__neighborLock.acquire() Neighborhood = lminus(self.__ClientNeighborhood, self.__ClientConnectionIPs) potentialconnect = sample(Neighborhood, min(len(Neighborhood), number)) for eachClient in potentialconnect: if self.__NumofConnections < self.__MaxNumConn: if eachClient not in self.__ClientConnectionIPs: cliSock = Mytcpsocket() ack1 = cliSock.Connect2Server(eachClient) ack2 = cliSock.sendmsg(self.__Addr[1]) ack3 = cliSock.recvmsg(BUFSIZ) # receive ACK if ack1 and ack2 and ack3 != 'closed': self.__NumofConnections += 1 self.__ClientConnectionSocks.append(cliSock) self.__ClientConnectionIPs.append(eachClient) t = MyThread(self.__upload, (cliSock, eachClient), self.__upload.__name__) self.__UploadThreadsLock.acquire() self.__UploadThreads.append(t) self.__UploadThreadsLock.release() self.__BWControlBoot.set() # start BW control self.__RateAllocBoot.set() # start rate allocation t.start() sleep(PROCESS_TIME) else: self.__ClientNeighborhood.remove(eachClient) else: break self.__connectionLock.release() self.__neighborLock.release()
def __Connect2Server(self, *targs): args = targs[0]; number = args[0]; videohash = args[1]; self.__connectionLock.acquire(); self.__neighborLock.acquire(); Neighborhood = lminus(self.__ServerNeighborhood, self.__ServerConnectionIPs) potentialconnect = sample(Neighborhood, min(len(Neighborhood),number)) for eachServer in potentialconnect: if self.__NumofConnections < self.__MaxNumConn: if eachServer not in self.__ServerConnectionIPs: servSock = Mytcpsocket() ack1 = servSock.Connect2Server(eachServer) ack2 = servSock.sendmsg(self.__Addr[1]) ack3 = servSock.recvmsg(BUFSIZ) # receive ACK if ack1 and ack2 and ack3!='closed': self.__NumofConnections += 1 self.__ServerConnectionSocks.append(servSock) self.__ServerConnectionIPs.append(eachServer) t = MyThread(self.__download,(servSock,eachServer,videohash), self.__download.__name__) t.start(); sleep(PROCESS_TIME); self.__downloadthreads.append(t); else: self.__ServerNeighborhood.remove(eachServer) else: break self.__connectionLock.release(); self.__neighborLock.release();
def __WaitforConnection(self, *targs): self.__tcpListenSock.InitServSock(self.__Addr,self.__MaxNumConn) while True: if self.__EXIT: return (tcpServSock, SERVER_ADDR) = self.__tcpListenSock.WaitforConn() self.__connectionLock.acquire(); servtcpsock = Mytcpsocket(tcpServSock) if self.__NumofConnections < self.__MaxNumConn: servport = servtcpsock.recvmsg(BUFSIZ) ack = servtcpsock.sendmsg('ACK') # send ACK SERVER_SERV_ADDR = (SERVER_ADDR[0],servport) if ((SERVER_SERV_ADDR in self.__ServerConnectionIPs) or (SERVER_SERV_ADDR == self.__ExcludedServerAddr) or (not ack) or servport == 'closed'): servtcpsock.close() else: self.__ServerConnectionSocks.append(servtcpsock) self.__ServerConnectionIPs.append(SERVER_SERV_ADDR) self.__NumofConnections += 1 if VERBOSE: print "...connected from:", SERVER_SERV_ADDR t = MyThread(self.__download, (servtcpsock,SERVER_SERV_ADDR,self.__currentvid),self.__download.__name__) t.start(); sleep(PROCESS_TIME); self.__downloadthreads.append(t) else: servtcpsock.close() # close if the number of connections exceeds max self.__connectionLock.release();
def GetPower(): global ser_laser, ser_motor, power_meter if GetPowerButton['text'] == "开始": if Sys_Init() is False: #系统初始化 GetPowerButton['text'] = "错误" return else: GetPowerButton['text'] = "执行" elif GetPowerButton['text'] == "执行": GetPowerButton['text'] = "停止" # 创建功率采集线程 GetPowerThread = MyThread.MyThread(func=Power_Get, args=()) GetPowerThread.setDaemon(True) GetPowerThread.start() # 创建计时线程 TimeCalcThread = MyThread.MyThread(func=Time_Calc, args=(TimeSet.get())) TimeCalcThread.setDaemon(True) TimeCalcThread.start() else: #激光器全局关 ser_laser.write([0xff]) ser_laser.write([0x06]) ser_laser.write([0x00]) ser_laser.write([0xdd]) ser_laser.close() #关闭激光驱动板控制接口 ser_motor.close() #关闭丝杠滑杆接口 GetPowerButton['text'] = "开始" return
def __init__(self, title='老梦的禅大师软件监控'): super().__init__() # 设置线程,监控线程和发邮件线程 self.tStart = MyThread.MyThread() self.tStart.sinOut.connect(self.startStatus) self.tSend = MyThread.MyThread() self.tSend.sinOut.connect(self.sendStatus) self.ipSet = [] # ip集合 self.title = title # 窗口标题 self.spider = CDSSpider() # 一个爬虫 self.SHOWHEAD = ['APP', '发行商', '类别', '发布时间', '下架时间'] self.initGui()
def bootashelper(self, videohash, segID, piecestodownload, excludedServerAddr): self.__BootedasUser = False self.__ExcludedServerAddr = excludedServerAddr self.__PiecestoDownload = piecestodownload # as a helper, specify pieces to download self.__PiecesperChunk = len(piecestodownload) self.__streamingPath = self.__cwd + os.sep + SERVER_PATH + os.sep + videohash + os.sep + 'seg' + str( segID) + FILE_SUFFIX self.__MetaPath = self.__cwd + os.sep + SERVER_PATH + os.sep + videohash + os.sep + 'seg' + str( segID) + META_SUFFIX self.__BufferFullWait.set() # no need to buffer download for helper #### need a mechanism to control this: need to be either too greedy or too conservative self.__BufferEmptyWait.set() ###### # register to the tracker t = MyThread(self.__commtotracker, (1, ), self.__commtotracker.__name__) t.start() sleep(PROCESS_TIME * 2) # choking t = MyThread(self.__choke, (1, ), self.__choke.__name__) t.start() sleep(PROCESS_TIME) # enable download self.__movieInitialize(videohash) sleep(PROCESS_TIME) self.__DownloadWait.wait() # wait until download is finished self.__EXIT = True return True
def MultiDownImg(domain,imgLinkList,dir): mth=MyThread.CMultiDownThread(10) for img in imgLinkList: imglink=domain+img["src"] imgName = imglink.split("/")[-1] imgPath=dir + "\\"+imgName print(imgPath) th = MyThread.CDownThread(imglink, imgPath) while not mth.AddThread(th): sleep(5) mth.join()
def main(): nfuncs = range(len(funcs)) print('*** single thread') for i in nfuncs: print('starting', funcs[i].__name__, 'at:', ctime()) print(funcs[i](n)) print(funcs[i].__name__, 'finished at:', ctime()) print('\n *** multiple threads') threads = [] for i in nfuncs: t = MyThread.MyThread(funcs[i], (n, ), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print(threads[i].getResult()) print('All done')
def __init__(self): super(Ui_MainWindow, self).__init__() self.num = 0 self.myThread = MyThread.MyThread() self.myThread.my_signal.connect(self.solt_set_text) self.myThread.quit_signal.connect(self.quitJob) self.filename = ""
def pushButton_converte_Clicked(self): try: if self.radioButton_single.isChecked(): if self.__excel_path and self.__excel_out_path and self.__conf_path: with open(self.__conf_path, encoding='utf-8') as f: jsonstr = f.read() dataconf = json.loads(jsonstr) self.thread = MyThread.ExcelThread() self.thread.signalOut.connect(self.setInfoText) self.thread.started.connect(self.convert_start) self.thread.finished.connect(self.convert_finished) self.thread.readPath = self.__excel_path self.thread.writePath = self.__excel_out_path self.thread.conf = dataconf self.thread.start() else: QMessageBox.warning(self, '警告', '未能正确配置!', QMessageBox.Ok) elif self.radioButton_multi.isChecked(): if self.__excel_path_list and self.__conf_path: with open(self.__conf_path, encoding='utf-8') as f: jsonstr = f.read() dataconf = json.loads(jsonstr) self.thread = MyThread.MultiExcelThread() self.thread.signalOut.connect(self.setInfoText) self.thread.started.connect(self.convert_start) self.thread.finished.connect(self.convert_finished) self.thread.readPath_list = self.__excel_path_list self.thread.conf = dataconf self.thread.start() else: QMessageBox.warning(self, '警告', '未能正确配置!', QMessageBox.Ok) except Exception as e: self.textBrowser_out.insertPlainText(str(e)) self.label_out_info.setText('转换失败!') self.pushButton_converte.setDisabled(False)
def MultiDownImgP(domain,subDirList,subsubImgDir,bParse=False): mth=MyThread.CMultiDownThread(10) for dir in subDirList: print("-------%s------" %dir) imgList=[] common.readLinkFile(dir+"\\img.txt",imgList) if not os.path.exists(dir + "\\%s\\"%subsubImgDir): os.makedirs(dir + "\\%s\\"%subsubImgDir) for img in imgList: if bParse: img=GetRealImg(img,".png") name=img.split("/")[-1] print(name) th=MyThread.CDownThread(domain+img,dir+"\\%s\\%s" %(subsubImgDir,name)) while not mth.AddThread(th): sleep(5) mth.join()
def bootasuser(self): self.__streamingPath = self.__cwd + os.sep + CLIENT_PATH + os.sep if not os.path.exists(self.__streamingPath): os.makedirs(self.__streamingPath) self.__PiecestoDownload = PIECE_IDS # as a user, download all the pieces self.__PiecesperChunk = PIECE_PER_CHUNK if VERBOSE: print 'User %s goes online at %s' % (self.__Addr,ctime()) # register to the tracker t = MyThread(self.__commtotracker,(1,),self.__commtotracker.__name__) t.start(); sleep(PROCESS_TIME); # choking t = MyThread(self.__choke,(1,),self.__choke.__name__) t.start(); sleep(PROCESS_TIME); # enable user prompt t = MyThread(self.__userprompt,(1,),self.__userprompt.__name__) # open a new thread for new requests t.start(); sleep(PROCESS_TIME);
def getRandForest(self): """ :param graph: :param amt_vaccination: :param total: :param start_sign: 生成树起始点的选择,0表示随机选择一个节点作为起始点,1表示的是选择一个度最大的节点作为起始点。 默认式0 :param diffusion_sign: 使用方法的标志位置,如果是0表示使用的是随机的方式,1表示使用的节点度大的点作为扩散点 默认是0 :return: 接种点集合 """ # 利用多线程生成多课子树 degree_dic = {} threads = [] index = 0 for i in range(self.tree_num): t = MyThread.MyThread(self._getTreeGraph, args=(self.graph, self.total, self.start_sign, self.diffusion_sign)) threads.append(t) t.start() point_number_list = [] result_list = [] index = 0 max_list = [] min_list = [] for t in threads: t.join() if index == 0: point_number_list = t.get_result().degree().keys() index = 1 result_list.append(t.get_result().degree().values()) max_list.append(max(t.get_result().degree().values())) min_list.append(min(t.get_result().degree().values())) temp_list = [] for i in range(len(point_number_list)): distance_best = 0.0 distance_worst = 0.0 for j in range(self.tree_num): distance_best = (max_list[j] - result_list[j][i])**2 + distance_best distance_worst = (min_list[j] - result_list[j][i])**2 + distance_worst distance_best = distance_best**(0.5) distance_worst = distance_worst**(0.5) temp_list.append(distance_best / (distance_best + distance_worst)) for i in range(len(point_number_list)): degree_dic[point_number_list[i]] = temp_list[i] vaccination_list = [ sorted(degree_dic.iteritems(), key=lambda b: b[1], reverse=True)[i][0] for i in range(self.amt_vaccination) ] return vaccination_list
def begin(tm=10): t = MyThread(scoreUpdateThreadFunction) t.start() print ("Waiting "+str(tm)+" second...") time.sleep(tm) print ("Done waiting.") t.stop() t.join() print ("Closed all threads.")
def main(): logging.info(f"start all at{ctime()}") threads = [] nloops = range(len(loops)) for i in nloops: print(f"这里是i:{i}") th = MyThread(loop, (i, loops[i]), "11") threads.append(th) for i in nloops: threads[i].start() for i in nloops: threads[i].join() logging.info(f"end all at{ctime()}")
def __WaitforConnection(self, *targs): self.__tcpSerSock.InitServSock(self.__Addr, self.__MaxNumConn) if VERBOSE: print "Waiting for connection..." while True: (tcpClientSock, CLIENT_ADDR) = self.__tcpSerSock.WaitforConn() self.__connectionLock.acquire() clitcpsock = Mytcpsocket(tcpClientSock) if self.__NumofConnections < self.__MaxNumConn: servport = clitcpsock.recvmsg(BUFSIZ) ack = clitcpsock.sendmsg('ACK') CLIENT_SERV_ADDR = (CLIENT_ADDR[0], servport) if ((CLIENT_SERV_ADDR in self.__ClientConnectionIPs) or (not ack) or servport == 'closed'): clitcpsock.close() else: self.__ClientConnectionSocks.append(clitcpsock) self.__ClientConnectionIPs.append(CLIENT_SERV_ADDR) self.__NumofConnections += 1 if VERBOSE: print "...connected from:", CLIENT_ADDR t = MyThread(self.__upload, (clitcpsock, CLIENT_SERV_ADDR), self.__upload.__name__) self.__UploadThreadsLock.acquire() self.__UploadThreads.append(t) self.__UploadThreadsLock.release() self.__BWControlBoot.set() # start BW control self.__RateAllocBoot.set() # start rate allocation t.start() sleep(PROCESS_TIME) else: clitcpsock.close( ) # close if the number of connections exceeds max self.__connectionLock.release()
def doTrans(self, command): try: if self.isOpen >= 0: send_str = self.entrySend.get() self.showLog("超时时间:%s" % send_str) self.showLog("开始交易...") t = MyThread.myThread(command, self.dll) t.setDaemon(True) t.start() t.join() return t.get_result() else: self.showLog("串口没有打开") except Exception as e: print(e) self.showLog("发送失败")
def start_test(self): MyThread.myThread1.set_flag('False') self.b1.config(state=DISABLED) self.b2.config(state=NORMAL) test_type = self.v1.get() device = self.v2.get() direction = self.v3.get() ratio = self.v4.get() speed = self.v5.get() max_steps = self.v6.get() auto = self.v7.get() if device == '' or device.isspace(): self.text_msglist.insert(END, 'please input device id\n', 'red') self.b1.config(state=NORMAL) return -1 elif auto == u'开启': try: ratio = float(ratio) except ValueError: self.text_msglist.insert(END, 'please input swipe precent\n', 'red') self.b1.config(state=NORMAL) return -1 if ratio < 0 or ratio >= 0.5: self.text_msglist.insert(END, 'precent range is [0,0.5)\n', 'red') self.b1.config(state=NORMAL) return -1 elif max_steps == '' or max_steps.isspace( ) or not max_steps.isdigit(): self.text_msglist.insert(END, 'please input swipe precent\n', 'red') self.b1.config(state=NORMAL) return -1 if auto == u'关闭': ratio = 0 max_steps = 0 thread1 = MyThread.myThread1(1, device, direction, speed, ratio, max_steps, test_type, auto, self.text_msglist) thread1.setDaemon(True) thread1.start()
def _proceeding(self): threads = [] funcs = [ self._processImage, self._saveVideoLocal, self._breaklog, self._emailCrtl ] nfuncs = len(funcs) args = [(self._q, self._cameraClient), (self.videoNum, self._q), (1, ), (1, 2)] names = ['getpicture', 'save', 'log', 'emailctrl'] for i in range(nfuncs): t = MyThread.MyThread(func=funcs[i], name=names[i], args=args[i]) threads.append(t) for i in range(nfuncs): if (i < 2): threads[i].setDaemon(True) for i in range(nfuncs): threads[i].start()
def boot(self): t = MyThread( self.__userprompt, (1, ), self.__userprompt.__name__) # open a new thread for new requests t.start() sleep(PROCESS_TIME) self.__socket.InitServSock(self.__Addr, self.__MaxNumConn) while True: (tcpCliSock, CIENT_ADDR) = self.__socket.WaitforConn() t = MyThread(self.__registerpeer, (tcpCliSock, CIENT_ADDR), self.__registerpeer.__name__ ) # open a new thread for new requests #self.__threads.append(t) t.start() sleep(PROCESS_TIME) # allow process time for the thread self.__inputLock.acquire() if self.__EXIT == 1: self.__socket.close() break self.__inputLock.release()
def main(): nfuncs = range(len(funcs)) print('*** SINGLE THREAD') for i in nfuncs: print('starting', funcs[i].__name__, 'at:', ctime()) print(funcs[i](n)) print(funcs[i].__name__, 'finished at:', ctime()) print('\n*** MULTIPLE THREADS') threads = [] for i in nfuncs: t = MyThread.MoreThread(funcs[i], (n, ), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print(threads[i].getResult()) print('all DONE')
def boot(self): t = MyThread(self.__userprompt,(1,),self.__userprompt.__name__) # open a new thread for new requests t.start(); sleep(PROCESS_TIME); self.__socket.InitServSock(self.__Addr,self.__MaxNumConn) while True: (tcpCliSock, CIENT_ADDR) = self.__socket.WaitforConn() t = MyThread(self.__registerpeer,(tcpCliSock,CIENT_ADDR), self.__registerpeer.__name__) # open a new thread for new requests #self.__threads.append(t) t.start(); sleep(PROCESS_TIME) # allow process time for the thread self.__inputLock.acquire() if self.__EXIT == 1: self.__socket.close(); break; self.__inputLock.release()
def makeThread(): """ 启动多线程计算 :return: """ day, hour, minute = getTime() if minute % 2 != 0: minute -= 1 t1 = MyThread.CalNumber(day, hour, minute) t1.start() t2 = MyThread.CalRank(day, hour, minute) t2.start() t3 = MyThread.CalThermodynamic(day, hour, minute) t3.start() t4 = MyThread.CalGuiding(day, hour, minute) t4.start() t5 = MyThread.CalAverage(day, hour, minute) t5.start() t6 = MyThread.CalBuy(day, hour, minute) t6.start() t7 = MyThread.CalPi(day, hour, minute) t7.start()
def bootashelper(self, videohash, segID, piecestodownload, excludedServerAddr): self.__BootedasUser = False self.__ExcludedServerAddr = excludedServerAddr self.__PiecestoDownload = piecestodownload # as a helper, specify pieces to download self.__PiecesperChunk = len(piecestodownload) self.__streamingPath = self.__cwd + os.sep + SERVER_PATH + os.sep + videohash + os.sep + 'seg' + str(segID) + FILE_SUFFIX self.__MetaPath = self.__cwd + os.sep + SERVER_PATH + os.sep + videohash + os.sep + 'seg' + str(segID) + META_SUFFIX self.__BufferFullWait.set() # no need to buffer download for helper #### need a mechanism to control this: need to be either too greedy or too conservative self.__BufferEmptyWait.set() ###### # register to the tracker t = MyThread(self.__commtotracker,(1,),self.__commtotracker.__name__) t.start(); sleep(PROCESS_TIME*2); # choking t = MyThread(self.__choke,(1,),self.__choke.__name__) t.start(); sleep(PROCESS_TIME); # enable download self.__movieInitialize(videohash); sleep(PROCESS_TIME); self.__DownloadWait.wait(); # wait until download is finished self.__EXIT = True return True
def on_actNew_triggered(self): """ Slot: When the user click the New button, this slot will receive the New signal. """ import Global # initialize the class attribute self.path2method = {} # create a file dialog to open an apk file dlg = QFileDialog(self) filename = dlg.getOpenFileName(self, self.tr("Open APK File"), QString(), self.tr("APK Files Odex Files(*.*)")) filetype = filename.split('.', 1)[1] # QMessageBox.warning(self ,'file', filetype) if filetype == 'apk': Global.CONFIG = { "CFG": 1, "Dalvik": 1, "Java": 0, "Bytecode": 1, "Smali": 1, "CallIn": 1, "CallOut": 1, "Permission": 1, "Manifest": 1 } #add support for odex if filetype == 'odex': Global.CONFIG = { "CFG": 1, "Dalvik": 1, "Java": 0, "Bytecode": 1, "Smali": 1, "CallIn": 1, "CallOut": 1, "Permission": 1, "Manifest": 0 } if not zipfile.is_zipfile(filename): msgbox = QMessageBox() msgbox.setText("Please select the APK file correctly!") msgbox.setWindowTitle("Warning!") msgbox.show() else: # create a progress dialog to show the progress # all pre-processing are done in a thread progress = ProgressDialog() thread = MyThread(progress, str(filename)) thread.start() progress.run() # judge this APK whether it is valid or invalid if not Global.APK.isVaildAPK(): msgbox = QMessageBox() msgbox.setText("This APK is invalid!") msgbox.setWindowTitle("Error!") msgbox.exec_() return # clear all the last apk's info self.listWidget_strings.clear() self.listWidget_classes.clear() # self.Graph.scene.clear() # self.Graph_call.scene.clear() self.plainTextEdit_dalvik.setPlainText("") self.plainTextEdit_java.setPlainText("") self.plainTextEdit_bytecode.setPlainText("") self.plainTextEdit_smali.setPlainText("") self.textEdit_permission.setText("") self.textEdit_call.setText("") self.textBrowser.setText("") self.plainTextEdit_dalvik.reset() # start to show some infomation of the apk self.Tab_APKInfo(Global.APK) self.Tab_Methods(Global.APK, Global.VM, Global.VMX) self.Tab_Strings() self.Tab_Classes() print "Before show information" if Global.CONFIG["Java"] == 1: self.Tab_Files(str(filename)) else: self.treeWidget_files.clear() if Global.CONFIG["Smali"] == 1 or Global.CONFIG["Manifest"] == 1: print "config to show apktool" self.apktool = APKtool() #yuan build callinout tree if Global.CONFIG["CallIn"] == 1 or Global.CONFIG["CallOut"] == 1: methodInvokeList = self.CL.get_methodInvoke() self.callInOut = CallInOut(methodInvokeList) # mcalltree = self.callInOut.callTree() else: self.textEdit_call.setText("") if Global.CONFIG["Permission"] == 1: self.Tab_Permission() else: self.textEdit_permission.setText("") if Global.CONFIG["Manifest"] == 1: self.Tab_Manifest() else: self.textBrowser.setText("") self.tabWidget_2.setCurrentIndex(4) self.tabWidget.setCurrentIndex(7)
zero = [0,0,0,1,0,0,0] one = [0,1,1,1,0,1,1] two = [0,0,1,0,1,0,0] three = [0,0,1,0,0,0,1] four = [0,1,0,0,0,1,1] five = [1,0,0,0,0,0,1] six = [1,0,0,0,0,0,0] seven = [0,0,1,1,0,1,1] eight = [0,0,0,0,0,0,0] nine = [0,0,0,0,0,0,1] seven_seg_digits = [zero,one,two,three,four,five,six,seven,eight,nine] ########## t = MyThread(target = input) t.start() #led = MyThread(target = led) #led.start() vol = MyThread(target = volControl) vol.start() stop = MyThread(target = terminate) stop.start() oldstate = 0 while 1: sevenSegWrite(sev_seg_led)
def startIOs(): ios = MyThread('ios') ios.start() ios.join()
def startAndroid(): android = MyThread('android') android.start() android.join()
def on_actNew_triggered(self): """ Slot: When the user click the New button, this slot will receive the New signal. """ import Global # initialize the class attribute self.path2method = {} # create a file dialog to open an apk file dlg = QFileDialog(self) filename = dlg.getOpenFileName(self, self.tr("Open APK File"), QString(), self.tr("APK Files Odex Files(*.*)")) filetype = filename.split('.', 1)[1] # QMessageBox.warning(self ,'file', filetype) if filetype == 'apk': Global.CONFIG = {"CFG":1, "Dalvik":1, "Java":0, "Bytecode":1, "Smali":1, "CallIn":1, "CallOut":1, "Permission":1, "Manifest":1} #add support for odex if filetype == 'odex': Global.CONFIG = {"CFG":1, "Dalvik":1, "Java":0, "Bytecode":1, "Smali":1, "CallIn":1, "CallOut":1, "Permission":1, "Manifest":0} if not zipfile.is_zipfile(filename): msgbox = QMessageBox() msgbox.setText("Please select the APK file correctly!") msgbox.setWindowTitle("Warning!") msgbox.show() else: # create a progress dialog to show the progress # all pre-processing are done in a thread progress = ProgressDialog() thread = MyThread(progress, str(filename)) thread.start() progress.run() # judge this APK whether it is valid or invalid if not Global.APK.isVaildAPK(): msgbox = QMessageBox() msgbox.setText("This APK is invalid!") msgbox.setWindowTitle("Error!") msgbox.exec_() return # clear all the last apk's info self.listWidget_strings.clear() self.listWidget_classes.clear() # self.Graph.scene.clear() # self.Graph_call.scene.clear() self.plainTextEdit_dalvik.setPlainText("") self.plainTextEdit_java.setPlainText("") self.plainTextEdit_bytecode.setPlainText("") self.plainTextEdit_smali.setPlainText("") self.textEdit_permission.setText("") self.textEdit_call.setText("") self.textBrowser.setText("") self.plainTextEdit_dalvik.reset() # start to show some infomation of the apk self.Tab_APKInfo(Global.APK) self.Tab_Methods(Global.APK, Global.VM, Global.VMX) self.Tab_Strings() self.Tab_Classes() print "Before show information" if Global.CONFIG["Java"] == 1: self.Tab_Files(str(filename)) else: self.treeWidget_files.clear() if Global.CONFIG["Smali"] ==1 or Global.CONFIG["Manifest"] ==1: print "config to show apktool" self.apktool = APKtool() #yuan build callinout tree if Global.CONFIG["CallIn"] == 1 or Global.CONFIG["CallOut"] == 1: methodInvokeList = self.CL.get_methodInvoke() self.callInOut = CallInOut(methodInvokeList) # mcalltree = self.callInOut.callTree() else: self.textEdit_call.setText("") if Global.CONFIG["Permission"] == 1: self.Tab_Permission() else: self.textEdit_permission.setText("") if Global.CONFIG["Manifest"] ==1: self.Tab_Manifest() else: self.textBrowser.setText("") self.tabWidget_2.setCurrentIndex(4) self.tabWidget.setCurrentIndex(7)
def multithreadedExecution(funlist): threads = MyThread.MyThread() threads.set_thread_func_list(funlist) threads.start()
from tkinter import * from MyThread import * from NBAScores import * from stdlib import * from ScoresGui import * from ScoreUpdateThread import * root = Tk() sb = NBAScoreGUI(root) t = MyThread(scoreUpdateThreadFunction) t.start() print ("Update Thread Started") root.mainloop() t.stop() t.join() print ("Update Thread Closed")
def boot(self, uploadBW): self.__uploadBW = uploadBW # force a virtual upload bandwidth; for testing reasons if VERBOSE: print 'Server %s goes online at %s' % (self.__Addr, ctime()) ####### This is fake, just for testing purpose ################ t = MyThread(self.__uploadBWControl, (1, ), self.__uploadBWControl.__name__) t.start() sleep(PROCESS_TIME) # rate allocation if not self.__isserver: t = MyThread(self.__rateallocation, (1, ), self.__rateallocation.__name__) t.start() sleep(PROCESS_TIME) # register to the tracker t = MyThread(self.__commtotracker, (1, ), self.__commtotracker.__name__) t.start() sleep(PROCESS_TIME) # listen to passive connections t = MyThread(self.__WaitforConnection, (1, ), self.__WaitforConnection.__name__) t.start() sleep(PROCESS_TIME) # actively connect to client t = MyThread(self.__Connect2Client, self.__MaxNumConn, self.__Connect2Client.__name__) t.start() sleep(PROCESS_TIME) # choking t = MyThread(self.__choke, (1, ), self.__choke.__name__) t.start() sleep(PROCESS_TIME) # user prompt t = MyThread( self.__userprompt, (1, ), self.__userprompt.__name__) # open a new thread for new requests t.start() sleep(PROCESS_TIME)
import MyThread import datetime import time def getTime(): day = int(datetime.datetime.now().strftime("%d")) hour = int(datetime.datetime.now().strftime("%H")) minute = int(datetime.datetime.now().strftime("%M")) return day, hour, minute if __name__ == '__main__': day, hour, minute = getTime() day = 26 t1 = MyThread.CalNumber(day, hour, minute) t1.start() t2 = MyThread.CalRank(day, hour, minute) t2.start() t3 = MyThread.CalThermodynamic(day, hour, minute) t3.start() t4 = MyThread.CalGuiding(day, hour, minute, "顺风大酒店") t4.start() time.sleep(60) db = Reserve() day, hour, minute = getTime() day = 26 while True: print("实时:{}号{}时{}分".format(day, hour, minute))
def boot(self, uploadBW): self.__uploadBW = uploadBW # force a virtual upload bandwidth; for testing reasons if VERBOSE: print 'Server %s goes online at %s' % (self.__Addr,ctime()) ####### This is fake, just for testing purpose ################ t = MyThread(self.__uploadBWControl,(1,),self.__uploadBWControl.__name__) t.start(); sleep(PROCESS_TIME); # rate allocation if not self.__isserver: t = MyThread(self.__rateallocation,(1,),self.__rateallocation.__name__) t.start(); sleep(PROCESS_TIME); # register to the tracker t = MyThread(self.__commtotracker,(1,),self.__commtotracker.__name__) t.start(); sleep(PROCESS_TIME); # listen to passive connections t = MyThread(self.__WaitforConnection,(1,),self.__WaitforConnection.__name__) t.start(); sleep(PROCESS_TIME); # actively connect to client t = MyThread(self.__Connect2Client,self.__MaxNumConn,self.__Connect2Client.__name__) t.start(); sleep(PROCESS_TIME); # choking t = MyThread(self.__choke,(1,),self.__choke.__name__) t.start(); sleep(PROCESS_TIME); # user prompt t = MyThread(self.__userprompt,(1,),self.__userprompt.__name__) # open a new thread for new requests t.start(); sleep(PROCESS_TIME);
import operations import time import MyThread start_time = time.perf_counter() for x in range(30): operations.random_numbers(1, 1000000) end_time = time.perf_counter() elapsed_time = end_time - start_time print("Without using thread library: " + str(elapsed_time)) start_time = time.perf_counter() for x in range(30): MyThread.myThread(x).start() end_time = time.perf_counter() elapsed_time = end_time - start_time print("Using thread library: " + str(elapsed_time))
def bootasuser(self): self.__streamingPath = self.__cwd + os.sep + CLIENT_PATH + os.sep if not os.path.exists(self.__streamingPath): os.makedirs(self.__streamingPath) self.__PiecestoDownload = PIECE_IDS # as a user, download all the pieces self.__PiecesperChunk = PIECE_PER_CHUNK if VERBOSE: print 'User %s goes online at %s' % (self.__Addr, ctime()) # register to the tracker t = MyThread(self.__commtotracker, (1, ), self.__commtotracker.__name__) t.start() sleep(PROCESS_TIME) # choking t = MyThread(self.__choke, (1, ), self.__choke.__name__) t.start() sleep(PROCESS_TIME) # enable user prompt t = MyThread( self.__userprompt, (1, ), self.__userprompt.__name__) # open a new thread for new requests t.start() sleep(PROCESS_TIME)
# -*- coding: utf-8 -*- """ Created on Wed Feb 6 16:15:09 2019 @author: mhmdk """ import MyThread thread1 = MyThread("1") thread1.run()
import os import time import MyThread filePath = "Image//" MyThread.myThread.filePath = filePath now = 1 allImage = os.listdir(filePath) for image in allImage: if image.endswith((".png", ".jpg")): thread = MyThread.myThread(str(now), image, now) thread.start() now = now + 1 time.sleep(0.05)
def __movieInitialize(self, videohash): ## dump all current # dump the current streaming if possible self.__bufferStatLock.acquire(); if self.__currentvid == videohash: self.__bufferStatLock.release(); return #### movie paramter initialization: self.__streamingRate = BYTES_PER_CHUNK/BUFFER_LENGTH self.__streamingBufferLength = 0 # in units of seconds self.__streamedNumofChunks = 0 # number of chunks that are streamed self.__bufferheadChunkID = 0 # the chunk ID in front of the buffer self.__bufferContent = [] # integer IDs self.__bufferPieceIDs = [] # string names self.__PiecesNowRequested = [] # pieces that are now requested self.__avaiPieceIDs = self.__PiecestoDownload # initialize available pieces to watch self.__streamingWait.clear(); self.__BufferFullWait.clear(); self.__BufferEmptyWait.clear(); if videohash != 'None': # if a movie was requested self.__NumofChunks = self.__movieHashNames[videohash][0] self.__NumofLeftPieces = self.__movieHashNames[videohash][1] self.__currentvid = videohash if self.__receivedFile != None: # close the opened file self.__receivedFile.close() if self.__BootedasUser: writeFilePath = self.__streamingPath + videohash + '.flv' #writeFilePath = self.__streamingPath + 'hancock-tsr2_h480p' + '.flv' else: writeFilePath = self.__streamingPath self.__MetaFile = open(self.__MetaPath,'w+b') self.__receivedFile=open(writeFilePath,'w+b') # open a writable file if self.__BootedasUser: t = MyThread(self.__bufferControl,(1,),self.__bufferControl.__name__); t.start(); sleep(PROCESS_TIME); # start buffer control t = MyThread(self.__streaming,(1,),self.__streaming.__name__); # start streaming t.start(); sleep(PROCESS_TIME); else: self.__BufferEmptyWait.set(); self.__BufferFullWait.set(); t = MyThread(self.__Connect2Server,(self.__MaxNumConn,videohash),self.__Connect2Server.__name__); t.start(); sleep(PROCESS_TIME); if self.__StartWaiting == False: # listen to active server to user connections self.__StartWaiting = True t = MyThread(self.__WaitforConnection,(1,),self.__WaitforConnection.__name__); t.start(); sleep(PROCESS_TIME); else: self.__NumofChunks = 0 self.__NumofLeftPieces = 0 self.__currentvid = 'None' # not watching any videos self.__bufferStatLock.release();