简体   繁体   中英

Multithreading with python?

I wrote a script to guess a pin, it kinda works but the script ignores the sleep command, and also the command threading.lock() does not working. so can you look through my script and tell how I can make my script better?

#!/usr/bin/env python -w 
#
# 
import time
import random
import os
import threading
import sys


lock = threading.Lock()
def Random(name,repeat):
    lock.acquire
    while repeat != 0:
        Pin = random.randint(0,9999)        
        print "[+] Trying: %d"%Pin;time.sleep(3)
        if Pin == 5656:
            os.system("clear");print '[+] Pin Found: %d' %Pin;time.sleep(3)
            sys.exit()
        repeat-= 1

    if lock.acquire():
        lock.release()


def Order(name,repeat):
    lock.acquire

    while repeat != 0:
        Pin = random.randint(0,9999)        
        print "[!] Trying: %d"%Pin;time.sleep(3)

        if Pin == 5656:
            os.system("clear");print '[+] Pin Found: %d' %Pin;time.sleep(3)
            sys.exit()
        repeat-= 1



    if lock.acquire():
        lock.release()




def Main():
    Brute_1 = threading.Thread(target=Random,args=('Random_Guess',10))
    Brute_2 = threading.Thread(target=Order,args=('Order_Guess',10))
    Brute_1.start()
    Brute_2.start()


if __name__=='__main__':
    Start = raw_input("Press Enter To Start")
    while 1:
        os.system("clear");
        Main()

The while loop at the end of the listing will create two new threads every time through. The sleep function is called by the new threads, not the main thread, so the main thread will go through the while loop as fast as it can. That will generate new threads by the thousands, until the system crashes. You think the sleep function isn't working but of course it is; it's just that every time you see a line printed on the console it's the first guess taken by a new thread. I don't think that's what you want. I don't know what you're trying to do so I can't help further.

Also as pasztorpisti hinted, lock.acquire is a function and needs to be called with function call syntax ( lock.acquire() ) or else nothing will happen. Having said that, you need to clean up the high-level structure first.

Once you acquire a lock, other threads are blocked when they try to acquire the same lock. The time.sleep function DOES NOT release the lock, so as long as Thread1 has the lock Thread2 cannot acquire it, even though Thread1 is sleeping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM