我是python的新手,我正在尝试用简单的菜单开发一个应用程序:
问题是,AFAIK总是有一个主线程,我应该同步主线程和在“选项1”中创建的新线程来访问(读/写)共享数据。
以下代码实际上有效,但是如果我取消注释行#with my_mutex:
以设置同步,那么应用程序将永远等待。
有没有我看不到的僵局? 我的任何推理都是错的?
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");
答案 0 :(得分:3)
while
中的count_thread
循环几乎从不释放互斥锁。
您应该更改它,以便仅在更改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;