学习Python5(Thread)

本文通过一个简单的多线程计数程序演示了如何使用线程锁来确保多个线程同时更新全局变量时的数据一致性。实验结果显示,在五个线程各进行一百万次递增操作后,最终计数值为五百万。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试代码

#coding:utf8
import thread, time, random

print '-'*25, '测试1', '-'*25
count = 0
lock = thread.allocate_lock()
def threadTest():
    global count, lock
    lock.acquire()
    for i in xrange(1000000):
        count += 1
    lock.release()
for i in range(5):
    thread.start_new_thread(threadTest, ()) #如果对start_new_thread函数不是很了解,不要着急,马上就会讲解
    # print thread.get_ident()
    # print thread.stack_size()
    time.sleep(0.1)
print count #count是多少呢?是10000 * 10 吗?

# print '-'*25, '测试2', '-'*25
# def threadFunc(a = None, b = None, c = None, d = None):
#     print time.strftime('%H:%M:%S', time.localtime()), a
#     time.sleep(1)    
#     print time.strftime('%H:%M:%S', time.localtime()), b
#     time.sleep(1)
#     print time.strftime('%H:%M:%S', time.localtime()), c
#     time.sleep(1)
#     print time.strftime('%H:%M:%S', time.localtime()), d
#     time.sleep(1)
#     print time.strftime('%H:%M:%S', time.localtime()), 'over'

# thread.start_new_thread(threadFunc, (3, 4, 5, 6))   #创建线程,并执行threadFunc函数。
# time.sleep(5)

# print '-'*25, '测试3:', '-'*25
# thread.start_new_thread(lambda : (thread.interrupt_main(), ), ())
# try:
#     time.sleep(2)
# except KeyboardInterrupt, e:
#     print 'error:', e
# print 'over'

测试结果

------------------------- 测试1 -------------------------
5000000
>>> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值