![]() ![]() When wait() is called, it unlocks the resource so the producer can acquire it and append a new integer to the list before notifying the consumer. The producer is still waiting at that time because of the time.sleep(1) so the consumer acquires the lock again then waits to get notified by the producer. Thread-2 acquires the lock, retrieves 159 and releases the lock. Thread-1 appends 159 to the list then notifies the consumer and releases the lock. Note that a call to wait() releases the lock so the producer can acquire the resource and do its work. Once the element is retrieved from the list, it releases the lock. It acquires the lock, checks if there is an integer in the list, if there is nothing, it waits to be notified by the producer. Print 'condition released by %s' % self.name Print 'condition notified by %s' % self.name Print '%d appended to list by %s' % (integer, self.name) Print 'condition acquired by %s' % self.name Append random integers to the integers list The source code can be found in threads/lock.py.ĭef _init_(self, integers, integers list of condition condition synchronization object I am just going to highlight the modifications relevant to locks. To solve our issue of 2 threads writing to the same file at the same time, we pass a lock to the FetchUrls constructor and we use it to protect the file write operation. if the state is locked: a call to release() changes the state to unlocked().if the state is unlocked: a call to release() raises a RuntimeError exception.if the state is locked: a call to acquire() blocks until another thread calls release().if the state is unlocked: a call to acquire() changes the state to locked.2 methods are used to manipulate them: acquire() and release(). Locks have 2 states: locked and unlocked. One way to do that is to use synchronization mechanisms like locks. ![]() We need to find a way to only have 1 thread writing to the file at a given time. ![]() The issue is that both threads are going to write to the file at the same time, resulting in a big mess. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |