0

I need to run 2 functions at the same time.

  1. the first function to received the input from the user and save the input inside a list
  2. the second one is to clear the list every 5 seconds.

Here's the code:

import time

a = [ ]
for i in range (1,10,1):
    x = raw_input(" Enter the Value : ")
    a.append(x)
    print "List Value : " , a
    time.sleep(1)

a[ : ] = [ ]
print " List Value : " , a
martineau
  • 119,623
  • 25
  • 170
  • 301
Munther
  • 3
  • 5
  • Do you need a cross-platform solution or is it acceptable to provide a solution for just one operating system? If so, which OS do you target? – Frerich Raabe Dec 22 '16 at 09:29
  • I do not think about the operating system, if operation system is different is the solution also different? – Munther Dec 22 '16 at 10:30

3 Answers3

1

In this case you need two threads for each function and a mutex for the list to ensure mutual exclusion.

from threading import Thread, Lock

def getUserData(arg_list):
    mutex.acquire()
    # handle user data
    mutex.release()

def clearList(arg_list):
    mutex.acquire()
    #clear list
    mutex.release()

# In main function
mutex = Lock()
userData = []

t1 = Thread(target = getUserData, args = (userData,))
t2 = Thread(target = clearList, args = (userData,))
t1.start()
t2.start()
while True:
  pass
FlipTack
  • 413
  • 3
  • 15
hannibal
  • 266
  • 4
  • 15
  • Thank you @hannibal , but when i run your code after i wite the handle user data and clear list , your code is not work correctly just run once and after i enter new value the program is do not apper anything unil i stopped it . – Munther Dec 22 '16 at 11:04
  • @hannibal , can you told me what is mean role for look function and also acquire and release functions .. i think from names ( acquire , release ) these fuction will acquire and release something but i do not what . – Munther Dec 22 '16 at 11:12
  • 1
    The name `list` is reserved in Python. It's better to use another name for the variable. – Fomalhaut Dec 22 '16 at 11:15
  • @Munther. For your question about Mutexes please refer to this link [link](http://stackoverflow.com/questions/34524/what-is-a-mutex) 1. In getUserData fucntion you need to release the lock as soon as the user finishes entering data. 2. In clearList you just need to check if the 5 sec waiting time is expired or not. If it is true acquire the mutex (or wait until getUserData releases it), clear the list and release the mutex again. – hannibal Dec 22 '16 at 11:27
1

If you're on macOS or Linux, you can use signals for this -- this doesn't require a lot of modification to your program. Here's an updated version:

import time
import signal

TIMEOUT = 10

a = [ ]

def clear(signum, frame):
    global a
    a = []
    signal.alarm(TIMEOUT)
signal.signal(signal.SIGALRM, clear)
signal.alarm(TIMEOUT)

for i in range (1,10,1):
    x = raw_input(" Enter the Value : ")
    a.append(x)
    print "List Value : " , a
    time.sleep(1)

a[ : ] = [ ]
print " List Value : " , a

The only difference here is that a signal handler is installed via signal.signal which is invoked everytime the signal.SIGALRM signal is triggered. The code then calls signal.alarm to cause signal.SIGLARM to be triggered in 10 seconds. The signal handler (clear) just clears the list and then schedules another signal.SIGARLM signal.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
  • Thank you @Frerich Raabe , i will try your code with linux , actually i am using windows , also you import signal library can you tell me more about this library . as for example what do you mean by : signal.alram() signal.signal(signal.SIGALRM, clear) – Munther Dec 22 '16 at 11:09
0

In order to run several functions at the same time, you should use different threads for them. In Python there're two standard libraries to do it: threading and multiprocessing. threading uses GIL to make you be able to access to global shared data from the threads' codes easily (about GIL read this: https://wiki.python.org/moin/GlobalInterpreterLock). I've written a simple example of using threading to solve your task. Enjoy:

import threading
from time import sleep

a = []

def input_task():
    while True:
        new_val = raw_input("Enter a new value: ")
        a.append(new_val)
        print "Your current list is", a

def clear_task():
    while True:
        del a[:]
        sleep(5)

input_thread = threading.Thread(target=input_task)
clear_thread = threading.Thread(target=clear_task)

input_thread.start()
clear_thread.start()

input_thread.join()
clear_thread.join()
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
  • 1
    Not such a good example. You need something like a `threading.Lock` to synchronize concurrent access to the shared `a` list variable. – martineau Dec 22 '16 at 09:21
  • Thank you very much for your example and for your time. – Munther Dec 22 '16 at 10:37
  • I will go to understand the threading , how it's work and threading functions. – Munther Dec 22 '16 at 10:41
  • @martineau , thank you for your command , but what do you mean by " to synchronize concurrent access to the shared a list variable " , so now th access to the shared a list variable is not synchronize . – Munther Dec 22 '16 at 11:15
  • @Munther He means that two parallel threads modify one shared list. And it's not good if they do it at the same time. The result may be incorrect. Fortunately, `threading` uses `GIL` that protects the list, so my program is valid. Read more about `GIL` and multithreading in Python. – Fomalhaut Dec 22 '16 at 11:18
  • @Munther Read this about shared sources: http://effbot.org/zone/thread-synchronization.htm . It can be useful if you develop more complex programs. – Fomalhaut Dec 22 '16 at 11:21
  • @Fomalhaut , i will read more about multithreading and Gil , i am just start with python so i do n't hear about threading before. Thank you very much. – Munther Dec 22 '16 at 11:42
  • Fomalhaut: I don't think you're correct about the GIL automatically protecting the shared list object from concurrent access. If it were true, one would never need to use something like a `Lock` instance in a Python program, since in reality because of the GIL, two threads of Python code _can_ never both be running at the same time within the same interpreter. @Munther: Suggest you read the Wikipedia article on [Concurrency control in operating systems](https://en.wikipedia.org/wiki/Concurrency_control#Concurrency_control_in_operating_systems) which also applies to threading. – martineau Dec 22 '16 at 14:09
  • @martineau Any function is a sequence of atomic instructions. GIL ensures that only one instruction is being executed at a moment of time. In the task I used `a.append` and `del a[:]` that make adding and deleting, and they are atomic (you can check it by your own with the help of the module `dis`). Therefore we may not use `Lock` to ensure the correct working of the code. `Lock` is needed if you want to pause a thread entering a section if another one hasn't finished working with it yet. Usually it's necessary if you do some complex changes with a shared source to ensure its consistency. – Fomalhaut Dec 22 '16 at 16:51
  • Fomalhaut: First of all it takes a total of 4 instructions to perform the `a.append(new_val)` with only the last one calling the internal `list.append` interpreter code to actually update the list. Secondly, even if the additional 3 instructions happen to be thread-switching safe, one shouldn't need to use the disassembler to determine if some snippet of code needs a lock or not to guarantee [mutual exclusion](https://en.wikipedia.org/wiki/Mutual_exclusion). Furthermore the bytecode generated can vary in different versions of Python—so what is actually generated can change without notice. – martineau Dec 22 '16 at 20:11
  • Fomalhaut: In summary, _all_ parts of the program where a shared resource is accessed should be protected from concurrent access—which will always work if implemented correctly even if it is not strictly needed in a few cases. It's possible doing so might degrade performance a consequential amount, but _only then_ is it worthwhile to attempt eliminating or at least minimize it away (aka optimization). – martineau Dec 22 '16 at 20:27