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 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 __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 __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 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 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 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 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 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 _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, 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)
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 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 startIOs(): ios = MyThread('ios') ios.start() ios.join()
def startAndroid(): android = MyThread('android') android.start() android.join()
def multithreadedExecution(funlist): threads = MyThread.MyThread() threads.set_thread_func_list(funlist) threads.start()
# -*- coding: utf-8 -*- """ Created on Wed Feb 6 16:15:09 2019 @author: mhmdk """ import MyThread thread1 = MyThread("1") thread1.run()
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()