logo
down
shadow

Lock variable in python in a loop


Lock variable in python in a loop

By : rayudu
Date : November 16 2020, 06:23 AM
To fix this issue I am trying to implement Producer consumer scenario in Python... The producer is supposed to cease lock variable if the queue is full and release it if it is not full... I am using the lock variable in loop , I added some notes on your code, which has some problems:
code :
def run(self):
        while True:
            customer=Customer()
            self.mutex.acquire()

            if self.queue.full():
                print "Queue is full : Cant Enter Critical Section"
                # NOTE 1: you have to release mutex here: self.mutex.release()
            elif not self.queue.full():
                # NOTE 2: other threads can enter after releasing the lock
                print self.mutex.release()

                self.mutex.acquire()
                #Critical Section
                self.queue.put(customer)
                print "Customer %d Enters the Queue with %d service " %(
                    customer.id,customer.serviceTime
                )
                self.mutex.release()
def run(self):
        while True:
            customer=Customer()
            self.mutex.acquire()

            if self.queue.full():
                print "Queue is full : Cant Enter Critical Section"

            elif not self.queue.full():
                # NOTE 2: other threads can enter after releasing the lock
                print self.mutex.release()

                self.mutex.acquire()
                #Critical Section
                self.queue.put(customer)
                print "Customer %d Enters the Queue with %d service " %(
                    customer.id,customer.serviceTime
                )
            # Note 1 alternative - release mutex (cancel 'if' branching effect)
            self.mutex.release()
>>> import threading
>>> lock = threading.Lock()
>>> lock.acquire()
True
>>> lock.acquire()


Share : facebook icon twitter icon
Python 3.x - Getting the state of caps-lock/num-lock/scroll-lock on Windows

Python 3.x - Getting the state of caps-lock/num-lock/scroll-lock on Windows


By : Sam
Date : March 29 2020, 07:55 AM
With these it helps You can use ctypes to load user32.dll and then call GetKeyState with nVirtKey = VK_CAPITAL (0x14)
code :
def get_capslock_state():
    import ctypes
    hllDll = ctypes.WinDLL ("User32.dll")
    VK_CAPITAL = 0x14
    return hllDll.GetKeyState(VK_CAPITAL)
Will lock in while loop make variable unreadable

Will lock in while loop make variable unreadable


By : user3093862
Date : March 29 2020, 07:55 AM
I hope this helps you . Assignments to an int are already atomic, and given that its volatile memory barriers are already in place. The lock is doing literally nothing.
Why do I get an infinite while loop even if I modify the lock variable?

Why do I get an infinite while loop even if I modify the lock variable?


By : tanoah
Date : March 29 2020, 07:55 AM
Does that help , Short answer
You forgot to declare guard as a volatile boolean.
code :
if(!guard)
{
    while(true)
    {
    }
}
public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}
private void write(String s) {
    try {
        synchronized (this) {
            ensureOpen();
            textOut.write(s);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush && (s.indexOf('\n') >= 0))
                out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}
While loop in python doesn't end when it contains a lock

While loop in python doesn't end when it contains a lock


By : Elie Hage
Date : March 29 2020, 07:55 AM
I hope this helps . Actually it's not just 1 thread that will give the next line is the return. There can be anywhere between 1 to 8.
In my executions, sometimes i got 1,3,4,5,6,7 or 1,2,3,4,5,6,7 or 1,4,5,6,7 or only 5,6,7 etc.
code :
import threading
import queue
import time

my_queue = queue.Queue()

lock = threading.Lock()

for i in range(50):
    my_queue.put(i)

def something_useful(CPU_number):
    while True:
        lock.acquire()
        if not my_queue.empty():
            print("CPU_C " + str(CPU_number) + ": " + str(my_queue.get()))
            lock.release()
        else:
            lock.release()
            break

    print("CPU_C " + str(CPU_number) + ": the next line is the return")

    return

number_of_threads = 8

practice_threads = []

for i in range(number_of_threads):
    thread = threading.Thread(target=something_useful, args=(i, ))
    practice_threads.append(thread)
    thread.start()
if not my_queue.empty():
    val = my_queue.get()
    lock.release()
    print("CPU_C " + str(CPU_number) + ": " + str(val))
    heavy_processing(val)  # While this is going on another thread can read the next val
variable locking in python thread fails to lock if multiple lock instance created?

variable locking in python thread fails to lock if multiple lock instance created?


By : user2655128
Date : March 29 2020, 07:55 AM
To fix the issue you can do In your first version, the Lock is created before the threads are ever started and is a global variable available to both thread. Hence, this single lock object is shared between the threads. The lock object will only allow one thread at a time to acquire it. While it's been acquired, the other thread invoking .acquire() will block until the other thread invokes .release(). And as you noted, your code works as expected.
In your second version, when you move the Lock creation into the thread function as a local variable. Hence, each thread invokes a different run of sample which creates a unique and different lock object. Each thread is always able to acquire the local lock variable without waiting because the other thread is always acquiring another lock. Hence, the s variable isn't really protected.
Related Posts Related Posts :
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • Creating a custom admin view
  • How do you get the user role of the currently logged in user in Ckan?
  • Speed up Numpy Meshgrid Command
  • Python error - name lengths
  • appending text to a global variable
  • Python Mistake - Number of letters in name
  • Searching for a sequence in a text
  • Testing logging output with pytest
  • How do I change my default working directory for Python (Anaconda) on VSCode?
  • .lower() for x in list, not working, but works in another scenario
  • Program gives error "List indices must not be string"
  • pyqt: Memory Usage
  • Confused about classes in Learn Python the Hard Way ex43?
  • Extracting unrecognized information from many CSV files
  • How do I connect to Postgresql server from Python?
  • Append rows to a pandas DataFrame without making a new copy
  • Scrapy: Importing a package from the project that's not in the same directory
  • launching Excel application using Python to view the CSV file , but CSV file is opening in read mode and cant view the d
  • Making a list in user-defined functions
  • Pyserial microcontroller to host communication
  • Plotting a line in between subplots
  • function not returning value. Error "NameError: name 'urlss' is not defined"
  • How to perform cartesian product with Tensorflow?
  • Multiple independent random number streams from single seed
  • I Need a simple and short python3 code that count secounds in a background process
  • No module named constants
  • from django 1.4 to django 1.5- argument 'verify_exists' what s replacement?
  • Slash replacement inside a raw string
  • Reordering columns/rows of a pivot_table?
  • MySQLdb.cursors.Cursor.execute does not work
  • Python module being reimported when imported at different places
  • Is the Session object from Python's Requests library thread safe?
  • Python Regex: Finding First and Last Names
  • Order by selection in List view of OpenERP 7.0
  • Reading input values in ipython notebook
  • List of dictionaries - how to read a specific value in a dictionary
  • writing os.system output to file
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org