亲宝软件园·资讯

展开

threading 多线程

autofelix 人气:0

一、创建一个线程

import threading

def func(s):
print(s)

if __name__ == '__main__':
# 创建线程
thread = threading.Thread(target=func, args=('hello',))
# 启动线程
thread.start()
# 等待线程结束
thread.join()

二、创建多个线程

import threading

def func(s):
print(s)

if __name__ == '__main__':
thread = [
threading.Thread(target=func, args=('1', ))
threading.Thread(target=func, args=('2', ))
]

[t.start() for t in thread]
[t.join() for t in thread]

三、线程同步

import time
import threading

# 创建锁
lock = threading.Lock()
# 全局变量
global_resource = [None] * 5

def change_resource(para, sleep):
# 请求锁
lock.acquire()
# 这段代码如果不加锁,第一个线程运行结束后global_resource中是乱的,输出为:结果是: ['hello', 'hi', 'hi', 'hello', 'hello']
# 第二个线程运行结束后,global_resource中还是乱的,输出为:结果是: ['hello', 'hi', 'hi', 'hi', 'hi']
global global_resource
for i in range(len(global_resource)):
global_resource[i] = para
time.sleep(sleep)
print("结果是:", global_resource)

# 释放锁
lock.release()

if __name__ == '__main__':
thread = [
threading.Thread(target=change_resource, args=('hi', 2))
threading.Thread(target=change_resource, args=('hello', 1))
]

[t.start() for t in thread]
[t.join() for t in thread]

# 结果是: ['hi', 'hi', 'hi', 'hi', 'hi']
# 结果是: ['hello', 'hello', 'hello', 'hello', 'hello']

四、递归锁

import time
import threading

# 使用成一个递归锁就可以解决当前这种死锁情况
rlock_hi = rlock_hello = threading.RLock()

def test_thread_hi():
# 初始时锁内部的递归等级为1
rlock_hi.acquire()
print('线程test_thread_hi获得了锁rlock_hi')
time.sleep(2)
# 如果再次获取同样一把锁,则不会阻塞,只是内部的递归等级加1
rlock_hello.acquire()
print('线程test_thread_hi获得了锁rlock_hello')
# 释放一次锁,内部递归等级减1
rlock_hello.release()
# 这里再次减,当递归等级为0时,其他线程才可获取到此锁
rlock_hi.release()

def test_thread_hello():
rlock_hello.acquire()
print('线程test_thread_hello获得了锁rlock_hello')
time.sleep(2)
rlock_hi.acquire()
print('线程test_thread_hello获得了锁rlock_hi')
rlock_hi.release()
rlock_hello.release()

if __name__ == '__main__':
thread = [
threading.Thread(target=test_thread_hi)
threading.Thread(target=test_thread_hello)
]

[t.start() for t in thread]
[t.join() for t in thread]

五、信号锁

import time
import threading

# 创建信号量对象,初始化计数器值为3
semaphore3 = threading.Semaphore(3)


def thread_semaphore(index):
# 信号量计数器减1
semaphore3.acquire()
time.sleep(2)
print('thread_%s is running...' % index)
# 信号量计数器加1
semaphore3.release()


if __name__ == '__main__':
# 虽然会有9个线程运行,但是通过信号量控制同时只能有3个线程运行
# 第4个线程启动时,调用acquire发现计数器为0了,所以就会阻塞等待计数器大于0的时候
for index in range(9):
threading.Thread(target=thread_semaphore, args=(index, )).start()

加载全部内容

相关教程
猜你喜欢
用户评论