简体   繁体   English

多线程-使用锁在两个线程之间交替

[英]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. 我正在尝试编写一个程序,希望使用该程序在两个线程thread1和thread2之间交替。 The tricky part is that I to make sure that the first thread that should begin execution is thread1. 棘手的部分是,我要确保应该开始执行的第一个线程是thread1。 This is the code I have so far but it keeps throwing me the runtime exception. 这是我到目前为止的代码,但是它总是使我抛出运行时异常。

lock1.release() error: release unlocked lock lock1.release()错误:释放解锁的锁

However lock1, in my opinion, is not an unlocked lock that is being released ! 但是,在我看来,lock1并不是正在释放的解锁锁!

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. 也就是说,如果线程1获得了锁,那么线程1必须释放它。 If thread1 acquires a lock and thread2 tries to release it, then thread2 will get an error. 如果线程1获取了一个锁,而线程2试图释放它,则线程2将得到一个错误。

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 . 如果要通知线程发生了某些事情,请使用事件对象条件对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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