Python线程:同步共享数据

时间:2014-04-26 13:27:28

标签: python multithreading synchronization deadlock

我是python的新手,我正在尝试用简单的菜单开发一个应用程序:

  1. 创建启动计数器的新线程
  2. 杀死主题
  3. 检查计数器值
  4. 退出应用程序,确保线程完成
  5. 问题是,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");
    

1 个答案:

答案 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;