简体   繁体   中英

Multithreading - Alternate between two threads using locks

I am trying to write a program using which I wish to alternate between two threads, thread1 and thread2. The tricky part is that I to make sure that the first thread that should begin execution is thread1. This is the code I have so far but it keeps throwing me the runtime exception.

lock1.release() error: release unlocked lock

However lock1, in my opinion, is not an unlocked lock that is being released !

This is the code I have so far

class Client: 
    #member variables
   def sendFile(self,lock1,lock2):
        sent = 0
        while (i<self.size):

            if(sent!=0):
                lock2.acquire()
            BadNet.transmit(self.clientSocket,message,self.serverIP,self.serverPort)
            lock1.release()
            sent+=1

        self.clientSocket.close()

    def receiveAck(self,lock1,lock2):
        print "\n Entered ack !"
        lock1.acquire()
        ack, serverAddress = self.clientSocket.recvfrom(self.buf)
        lock2.release()



if __name__ == "__main__":
    lock1 = Lock()
    lock2 = Lock()
    client = Client();
    client.readFile();
    thread1 = Thread(target = client.sendFile, args=[lock1,lock2])
    thread2 = Thread(target = client.receiveAck, args=[lock1,lock2])
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

You're getting the error because you have a thread that's trying to release a lock that it didn't acquire. Locks are specific to threads. That is, if thread1 acquires a lock, then thread1 has to release it. If thread1 acquires a lock and thread2 tries to release it, then thread2 will get an error.

If a thread didn't acquire a lock, then that thread can't release the lock.

You are trying to use locks for something they're not meant for. Locks are used for mutual exclusion, not messaging. If you want to notify a thread that something has happened, use an event object or a condition object .

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