Python中线程资源共享的问题

来源:互联网 发布:最新淘宝客服用语大全 编辑:程序博客网 时间:2024/06/11 12:35

       Python中线程全局变量是共享的,这一点与进程不同,在进程中所有进程之间的资源都是无关的,不共享的,所以在进程中使用进程之间的通信机制,比如queue。

      Python线程中非全局变量是不共享的,两个线程即便是运行同一函数,但是在函数中的非全局变量是不相关的,

from threading import Threadimport threading, timedef test1():    g_num = 100    name = threading.current_thread().name    print('---线程的名字是%s' % name)    if name == 'Thread-1':        g_num += 1        print()    else:        time.sleep(2)    print('---线程的名字是%s--g_num=%d' % (name, g_num))p1 = Thread(target=test1)p1.start()p2 = Thread(target=test1)p2.start()
上面这段代码的运行结果是:

---线程的名字是Thread-1---线程的名字是Thread-1--g_num=101---线程的名字是Thread-2---线程的名字是Thread-2--g_num=100
可以很清楚的看到线程1和2虽然都运行了test1(),但是非全局变量的结果是互不干扰的。

原创粉丝点击