Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different way to implement this threading?

I'm trying out threads in python. I want a spinning cursor to display while another method runs (for 5-10 mins). I've done out some code but am wondering is this how you would do it? i don't like to use globals, so I assume there is a better way?

c = True 

def b():
    for j in itertools.cycle('/-\|'):
        if (c == True):
            sys.stdout.write(j)
            sys.stdout.flush()
            time.sleep(0.1)
            sys.stdout.write('\b')
        else:
            return

def a():
    global c
    #code does stuff here for 5-10 minutes
    #simulate with sleep
    time.sleep(2)
    c = False

Thread(target = a).start()
Thread(target = b).start()

EDIT:

Another issue now is that when the processing ends the last element of the spinning cursor is still on screen. so something like \ is printed.

like image 577
Paul Avatar asked Mar 24 '23 00:03

Paul


1 Answers

You could use events: http://docs.python.org/2/library/threading.html

I tested this and it works. It also keeps everything in sync. You should avoid changing/reading the same variables in different threads without synchronizing them.

#!/usr/bin/python

from threading import Thread
from threading import Event
import time
import itertools
import sys

def b(event):
    for j in itertools.cycle('/-\|'):
        if not event.is_set():
            sys.stdout.write(j)
            sys.stdout.flush()
            time.sleep(0.1)
            sys.stdout.write('\b')
        else:
            return

def a(event):
    #code does stuff here for 5-10 minutes
    #simulate with sleep
    time.sleep(2)
    event.set()

def main():
    c = Event()
    Thread(target = a, kwargs = {'event': c}).start()
    Thread(target = b, kwargs = {'event': c}).start()

if __name__ == "__main__":
    main()

Related to 'kwargs', from Python docs (URL in the beginning of the post):

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
...
    kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
like image 166
Mihai Avatar answered Apr 05 '23 04:04

Mihai