python中threading产生死锁_python多线程(一)——_thread & threading & 线程共享变量 & 互斥锁 & 死锁...

线程也是实现多任务的一种方式,一个进程中,也经常需要同时做多件事,就需要同时运行多个‘子任务’,这些子任务就是线程。一个进程可以拥有多个并行的线程,其中每一个线程,共享当前进程的资源。

线程可以看出是轻量级的进程。多个线程共享内存,线程切换的开销小

进程和线程在使用上各有优缺点: 线程执行开销小, 但不利于资源的管理和保护, 而进程正相反。

在Python 程序中,可以通过“_thread”和 threading(推荐使用)这两个模块来处理线程。在 Python3 中, thread 模块已经废弃。可以使用 threading 模块代替。所以,在 Python3中不能再使用 thread 模块,但是为了兼容 Python3 以前的程序,在 Python3 中将 thread 模块重命名为“_thread”

使用_thread 模块

创建线程

当使用 thread 模块来处理线程时,可以调用里面的函数 start_new_thread()来生成一个新的线程

import _thread

import time

def fun1():

print('开始运行fun1')

time.sleep(4)

print('运行fun1结束')

def fun2():

print('开始运行fun2')

time.sleep(2)

print('运行fun2结束')

if __name__=='__main__':

print('主进程开始运行')

#启动一个线程运行函数 fun1

_thread.start_new_thread(fun1,())

#启动一个线程运行函数 fun2

_thread.start_new_thread(fun2,())

time.sleep(6)

print('主进程结束运行')

f39464e095aa3664b4fff9d2b4f2afba.png

b63a17edf7783ed27d587245465b5930.png

fun1和fun2谁先开始不一定

为线程传递参数

import _thread

import time

def fun1(thread_name,delay):

print('线程{0}开始运行 fun1'.format(thread_name))

time.sleep(delay)

print('线程{0}运行 fun1 结束'.format(thread_name))

def fun2(thread_name,delay):

print('线程{0}开始运行 fun2'.format(thread_name))

time.sleep(delay)

print('线程{0}运行 fun2 结束'.format(thread_name))

if __name__=='__main__':

print('开始运行')

#启动一个线程运行函数 fun1

_thread.start_new_thread(fun1,('thread-1',4))

#启动一个线程运行函数 fun2

_th

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python ,可以使用互斥锁(mutex)来实现多线程的互斥操作。互斥锁是一种同步原语,它能确保在同一时刻只有一个线程可以进入被保护的临界区。 下面是一个简单的示例,演示了如何使用互斥锁来保护共享资源: ```python import threading # 创建一个互斥锁对象 mutex = threading.Lock() # 共享资源 shared_resource = 0 def increment(): global shared_resource for _ in range(1000000): # 使用互斥锁来保护共享资源 mutex.acquire() shared_resource += 1 mutex.release() def decrement(): global shared_resource for _ in range(1000000): # 使用互斥锁来保护共享资源 mutex.acquire() shared_resource -= 1 mutex.release() # 创建两个线程 t1 = threading.Thread(target=increment) t2 = threading.Thread(target=decrement) # 启动线程 t1.start() t2.start() # 等待线程结束 t1.join() t2.join() print("Shared resource value:", shared_resource) ``` 在上面的示例,我们使用了 `threading.Lock()` 创建了一个互斥锁对象 `mutex`。在 `increment()` 和 `decrement()` 函数,我们使用 `mutex.acquire()` 来获取锁,并使用 `mutex.release()` 来释放锁。这样可以确保在任意时刻只有一个线程可以访问共享资源 `shared_resource`。 请注意,互斥锁是一种比较低级的同步原语,如果使用不当可能会导致死锁等问题。因此,在编写多线程代码时,需要仔细考虑锁的使用方式,以避免潜在的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值