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



原文地址:https://www.cnblogs.com/fonyer/p/9784866.html