python 线程

1、线程类

import threading 
import time 

class MyThread(threading.Thread):
	"""docstring for MyThread"""
	def run(self):
		for x in range(2):
			time.sleep(1)
			msg = "I'm "+self.name+"@"+str(x)
			print(msg)	

def main():
	for x in range(5):
		t = MyThread()
		t.start()	


if __name__ == '__main__':
	main()
I'm Thread-3@0
I'm Thread-2@0
I'm Thread-5@0
I'm Thread-4@0
I'm Thread-1@0
I'm Thread-3@1
I'm Thread-2@1
I'm Thread-5@1
I'm Thread-1@1
I'm Thread-4@1

2、锁

from threading import Thread,Lock
import time 
g_num = 0

def thread_1():
	global g_num
	#上锁
	mutex.acquire()
	for i in range(1000000):
		g_num += 1
	#解锁	
	mutex.release()
	print("thread_1:g_num is %d"%g_num)

def thread_2():
	global g_num
	#上锁
	mutex.acquire()
	for i in range(1000000):
		g_num += 1
	#解锁	
	mutex.release()
	print("thread_2:g_num is %d"%g_num)		

#创建锁
mutex = Lock()
t1 = Thread(target=thread_1)	
t1.start()

t2 = Thread(target=thread_2)	
t2.start()
thread_1:g_num is 1000000
thread_2:g_num is 2000000


3、python伪多线程:GIL 全局解释器锁的原因。

     可通过加载第三方类库,来实现多线程。

cat loop.c 

void DeadLoop()
{
        while(1)
                {
                        ;
                }
}
编译动态库

gcc loop.c -shared -o libdeadloop.so

cat thread-05.py

#python伪多线程:GIL 全局解释器锁
#将c语言文件生成动态库:gcc loop.c -shared -o libdeadloop.so
from ctypes import *
from threading import Thread 
#加载动态库(c语音)
lib = cdll.LoadLibrary("./libdeadloop.so")

#创建一个子线程,让其执行c语言编写的函数
t = Thread(target=lib.DeadLoop)
t.start()

#主线程也调用c语言的函数
#lib.DeadLoop()
while True:
	pass



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值