上一页 1 ··· 8 9 10 11 12 13 14 15 16 ··· 18 下一页
摘要: 1 import time 2 from threading import Thread,Lock 3 #创建3把互斥锁 4 lock1 = Lock() 5 lock2 = Lock() 6 lock3 = Lock() 7 #对lock2和lock3上锁 8 lock2.acquire() 9 阅读全文
posted @ 2020-04-11 23:04 小他_W 阅读(163) 评论(0) 推荐(0) 编辑
摘要: 1 import time 2 from threading import Thread,Lock 3 #定义全局变量num 4 num=0 5 #创建一把互斥锁 6 lock = Lock() 7 def test1(): 8 global num 9 ''' 10 在两个线程中都调用上锁的方法, 阅读全文
posted @ 2020-04-11 22:46 小他_W 阅读(133) 评论(0) 推荐(0) 编辑
摘要: 锁有两种状态——锁定和未锁定。某个线程要更改共享数据时,先将其锁定,此时资源的状态为“锁定”,其他线程不能更改;直到该线程释放资源,将资源的状态变成“非锁定”状态,其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进行写入操作,从而保证了多线程情况下数据的正确性。 使用 Thread 对象的 阅读全文
posted @ 2020-04-11 22:41 小他_W 阅读(152) 评论(0) 推荐(0) 编辑
摘要: 1 import time 2 from threading import* 3 #定义全局变量num 4 num = 0 5 def test1(): 6 global num 7 for i in range(100000): 8 num+=1 9 print('test1输出num:',num 阅读全文
posted @ 2020-04-11 22:29 小他_W 阅读(405) 评论(0) 推荐(0) 编辑
摘要: 在一个进程内所有线程共享全局变量,多线程之间的数据共享比多进程要好。但是可能造成多个进程同时修改一个变量(即线程非安全),可能造成混乱。 1 import time 2 from threading import * 3 #定义全局变量num 4 num=10 5 def test1(): 6 gl 阅读全文
posted @ 2020-04-11 22:12 小他_W 阅读(1281) 评论(0) 推荐(0) 编辑
摘要: 在Python中,通过继承类threading.Thread的方式来创建一个线程。这种方法只要重写类threading.Thread中的方法run(),然后再调用方法start()就能创建线程,并运行方法run()中的代码。 1 import threading 2 import time 3 de 阅读全文
posted @ 2020-04-11 22:07 小他_W 阅读(493) 评论(0) 推荐(0) 编辑
摘要: 在Python3程序中,对多线程支持最好的是threading模块,使用这个模块,可以灵活地创建多线程程序,并且可以在多线程之间进行同步和通信。 1 Thread(group=None, target=None, name=None, args=(), kwargs={}) 其中target: 要执 阅读全文
posted @ 2020-04-11 21:50 小他_W 阅读(187) 评论(0) 推荐(0) 编辑
摘要: 1 import _thread 2 import time 3 def fun1(thread_name,delay): 4 print('开始运行fun1,线程的名:',thread_name) 5 time. sleep(delay) 6 print('运行fun1结束') 7 8 def f 阅读全文
posted @ 2020-04-11 21:32 小他_W 阅读(3497) 评论(0) 推荐(0) 编辑
摘要: 在Python程序中,可以通过两种方式来使用线程:使用函数或者使用类来包装线程对象。当使用thread模块来处理线程时,可以调用里面的函数start_new_thread()来生成一个新的线程。 1 _thread.start_new_thread ( function, args[, kwargs 阅读全文
posted @ 2020-04-11 20:53 小他_W 阅读(246) 评论(0) 推荐(0) 编辑
摘要: 1 from multiprocessing import* 2 from time import sleep 3 #定义写入的方法 4 def write(q): 5 a = ['a','b','c','d'] 6 for i in a: 7 print('开始写入的值:%s'%i) 8 q.pu 阅读全文
posted @ 2020-04-10 22:40 小他_W 阅读(206) 评论(0) 推荐(0) 编辑
上一页 1 ··· 8 9 10 11 12 13 14 15 16 ··· 18 下一页