<jupyter_start><jupyter_text>python 多线程专题1、线程创建<jupyter_code>'''
threading.current_thread()表示当前线程，可以用name或getName()获取线程名称
'''
import threading
import time
def fun():
    print('The {0}  starting\n'.format(threading.current_thread().name))
    time.sleep(1)
    print('The {0} is end\n'.format(threading.current_thread().getName()))
if __name__=='__main__':
    print('The {0} is starting\n'.format(threading.current_thread().name))
    for _ in range(5):
          th = threading.Thread(target = fun)
          th.start()
    print('The {0} is ended\n'.format(threading.current_thread().name))
'''
线程创建，通过类的方式
__author__ = jyb
'''
import threading

class threadTest(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        print('%s is running'%threading.current_thread().name)
th1 = threadTest()
print('%s is running'%threading.current_thread().name)
th1.start()


"""
join()函数的用法
"""
from threading import Thread
import time 
t = time.time()

def myfun():
    time.sleep(1)
    print(1)
if __name__ =='__main__':
    th_list = [] 
    for _ in range(5):
        th = threading.Thread(target = myfun)
        th.start()
        th_list.append(th)
    for threadInstance in th_list:
        threadInstance.join()
    print(time.time()-t)<jupyter_output>111
1


1
1.1200637817382812<jupyter_text>2、 线程锁机制 LOCK锁，RLOCK锁<jupyter_code>"""
Locak
"""
import time
import threading
threadlock = threading.Lock()
a =100 
def consumer():
    threadlock.acquire()
    global a 
    a = a-1   
    threadlock.release()
def producer():
    threadlock.acquire()
    global a
    a = a+1
    threadlock.release
       
th1 = threading.Thread(target=consumer)
th1.start()
th2 = threading.Thread(target=producer)
th2.start()
print(a)

'''
RLOCK 锁，可重入锁，同一线程可以锁多次，锁的次数和释放次数要对应

'''
import threading
rlock = threading.RLock()
def myfun():
    print('%s is apply for a lock firstly\n'%threading.current_thread().name)
    if(rlock.acquire()):
        print('%s get a lock successfully \n'%threading.current_thread().name)
    time.sleep(1)
    
    print('%s is apply for a lock again\n'%threading.current_thread().name)
    if(rlock.acquire()):
        print('%s get a lock again successfully\n'%threading.current_thread().name)
    
    time.sleep(1)
    print('%s release a lock firstly\n'%threading.current_thread().name)
    rlock.release()
    
    time.sleep(1)
    print('%s release a lock again\n'%threading.current_thread().name)  
    rlock.release()
    
    
th1 = threading.Thread(target =myfun,name='threading-1')
th2 = threading.Thread(target = myfun,name='threading-2')
th3 = threading.Thread(target=myfun,name='threading-3')

th1.start()
th2.start()
th3.start()<jupyter_output>threading-1 is apply for a lock firstly

threading-1 get a lock successfully 

threading-2 is apply for a lock firstly
threading-3 is apply for a lock firstly


threading-1 is apply for a lock again

threading-1 get a lock again successfully

threading-1 release a lock firstly

threading-1 release a lock again

threading-3 get a lock successfully 

threading-3 is apply for a lock again

threading-3 get a lock again successfully

threading-3 release a lock firstly

threading-3 release a lock again

threading-2 get a lock successfully 

threading-2 is apply for a lock again

threading-2 get a lock again successfully

threading-2 release a lock firstly

threading-2 release a lock again<jupyter_text>即使存在多核的时候，python多进程是真正的并行，而多线程是伪并行，实际上他只是交替执行。是什么导致多线程，只能交替执行呢？是一个叫GIL（Global Interpreter Lock，全局解释器锁）的东西。什么是GIL呢？ 每个python进程有一个GIL锁，任何Python线程执行前，必须先获得GIL锁，然后，每执行100条字节码，解释器就自动释放GIL锁，让别的线程有机会执行。这个GIL全局锁实际上把所有线程的执行代码都给上了锁，所以，多线程在Python中只能交替执行，即使100个线程跑在100核CPU上，也只能用到1个核。  3、线程通信机制： condition event queue<jupyter_code>a = []
dir(iter(a))

b =(x for x in range(10))
dir(b)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12317327766179541, 'fraction_numerical': 0.022703549060542796, 'mean_word_length': 4.286896551724138, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '508217', 'license': 'Apache-2.0', 'n_tokens_mistral': 1541, 'n_tokens_neox': 1577, 'n_words': 304, 'path': 'Threading.ipynb', 'repo_name': 'jackjiang88/python_learning', 'size': '3832'}