Ricardo
Ricardo

Reputation: 8291

Python threads: synchronize shared data

Im new in python, I'm trying to develop an application with simple menu:

  1. Create new thread which starts a counter
  2. Kill the thread
  3. Check the counter value
  4. Exit from application ensuring the thread go finish

The thing is, AFAIK there is always a main thread and I should synchronize main thread and the new thread created in the "option 1" to access (read/write) the shared data.

The following code actually works, but if I uncomment the lines #with my_mutex: to set synchronization then the application waits forever.

Is there a deadlock that I don't see? Any of my reasoning is wrong?

import time;
import threading;

#shared data
go_on = True;
count = 0;
my_mutex = threading.Lock();

def  count_thread():
    global go_on;
    global count;
    global my_mutex;
    c = True;
    while c:
        with my_mutex:
            count += 1;
            time.sleep(1);
            if go_on == False:
                c = False;



def create_new_thread():
    t1 = threading.Thread(target=count_thread, args=());
    t1.start();


while True:
    print("Select an option");
    print("1. Create a new thread");
    print("2. Kill the current thread");
    print("3. Check counter");
    print("4. Exit");

    user_input = int(input());

    if user_input==1:
        create_new_thread();

    elif user_input==2:
        #with my_mutex:
            go_on = False;

    elif user_input==3:
        #with my_mutex:
            print("Current value: "+str(count));

    elif user_input==4:
        #with my_mutex:
            go_on = False;
            break;

    else:
        print("Invalid option");

Upvotes: 0

Views: 403

Answers (1)

Roland Smith
Roland Smith

Reputation: 43523

The while loop in count_thread almost never releases the mutex.

You should probably change it so the lock is only held when changing count.

def  count_thread():
    global go_on;
    global count;
    global my_mutex;
    c = True;
    while c:
        with my_mutex:
            count += 1;
        time.sleep(1);
        if go_on == False:
            c = False;

Upvotes: 3

Related Questions