python之系统编程 --线程
###########使用线程完成多任务################
from threading import Thread
import time #1. 如果多个线程执行的都是同一个函数的话,各自之间不会有影响,各是个的
def test():
print("----昨晚喝多了,下次少喝点---")
time.sleep(1) for i in range(5):
t = Thread(target=test)
t.start()
#############使用类的方式创建线程完成任务###########
import threading
import time class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字
print(msg) if __name__ == '__main__':
t = MyThread()
t.start()
执行结果:
[root@master process]# python3 09-thread.py
I'm Thread-1 @ 0
I'm Thread-1 @ 1
I'm Thread-1 @ 2
###############线程之间共享全局变量#########
from threading import Thread
import time #线程之间共享全局变量
g_num = 100 def work1():
global g_num
for i in range(3):
g_num += 1 print("----in work1, g_num is %d---"%g_num) def work2():
global g_num
print("----in work2, g_num is %d---"%g_num) print("---线程创建之前g_num is %d---"%g_num) t1 = Thread(target=work1)
t1.start() #延时一会,保证t1线程中的事情做完
time.sleep(1) t2 = Thread(target=work2)
t2.start()
############线程之间共享全局变量带来的问题############
from threading import Thread
import time g_num = 0 def test1():
global g_num
for i in range(1000000):
g_num += 1 print("---test1---g_num=%d"%g_num) def test2():
global g_num
for i in range(1000000):
g_num += 1 print("---test2---g_num=%d"%g_num) p1 = Thread(target=test1)
p1.start() #time.sleep(3) #取消屏蔽之后 再次运行程序,结果会不一样,,,为啥呢? p2 = Thread(target=test2)
p2.start() print("---g_num=%d---"%g_num)
############把列表当做参数传递给线程############
from threading import Thread
import time def work1(nums):
nums.append(44)
print("----in work1---",nums) def work2(nums):
#延时一会,保证t1线程中的事情做完
time.sleep(1)
print("----in work2---",nums) g_nums = [11,22,33] t1 = Thread(target=work1, args=(g_nums,))
t1.start() t2 = Thread(target=work2, args=(g_nums,))
t2.start()
###############避免多线程对共享数据出错的方式###########
from threading import Thread
import time g_num = 0
g_flag = 1 def test1():
global g_num
global g_flag
if g_flag == 1:
for i in range(1000000):
g_num += 1 g_flag = 0 print("---test1---g_num=%d"%g_num) def test2():
global g_num
#轮询
while True:
if g_flag != 1:
for i in range(1000000):
g_num += 1
break print("---test2---g_num=%d"%g_num) p1 = Thread(target=test1)
p1.start() #time.sleep(3) #取消屏蔽之后 再次运行程序,结果会不一样,,,为啥呢? p2 = Thread(target=test2)
p2.start() print("---g_num=%d---"%g_num)
##############使用互斥锁解决共享数据出错问题##################
代码例子:
from threading import Thread, Lock
import time g_num = 0 def test1():
global g_num
#这个线程和test2线程都在抢着 对这个锁 进行上锁,如果有1方成功的上锁,那么导致另外
#一方会堵塞(一直等待)到这个锁被解开为止
mutex.acquire()
for i in range(1000000):
g_num += 1
mutex.release()#用来对mutex指向的这个锁 进行解锁,,,只要开了锁,那么接下来会让所有因为
#这个锁 被上了锁 而堵塞的线程 进行抢着上锁 print("---test1---g_num=%d"%g_num) def test2():
global g_num
mutex.acquire()
for i in range(1000000):
g_num += 1
mutex.release() print("---test2---g_num=%d"%g_num) #创建一把互斥锁,这个锁默认是没有上锁的
mutex = Lock() p1 = Thread(target=test1)
p1.start() #time.sleep(3) #取消屏蔽之后 再次运行程序,结果会不一样,,,为啥呢? p2 = Thread(target=test2)
p2.start() print("---g_num=%d---"%g_num)
#############多线程使用非共享变量################
from threading import Thread
import threading
import time def test1():
#注意:
# 1. 全局变量在多个线程中 共享,为了保证正确运行需要锁
# 2. 非全局变量在每个线程中 各有一份,不会共享,当然了不需要加锁
name = threading.current_thread().name
print("----thread name is %s ----"%name)
g_num = 100
if name == "Thread-1":
g_num += 1
else:
time.sleep(2)
print("--thread is %s----g_num=%d"%(name,g_num)) #def test2():
# time.sleep(1)
# g_num = 100
# print("---test2---g_num=%d"%g_num) p1 = Thread(target=test1)
p1.start() p2 = Thread(target=test1)
p2.start()
执行结果:
###################同步#################
同步的应用:
from threading import Thread,Lock
from time import sleep class Task1(Thread):
def run(self):
while True:
if lock1.acquire():
print("------Task 1 -----")
sleep(0.5)
lock2.release() class Task2(Thread):
def run(self):
while True:
if lock2.acquire():
print("------Task 2 -----")
sleep(0.5)
lock3.release() class Task3(Thread):
def run(self):
while True:
if lock3.acquire():
print("------Task 3 -----")
sleep(0.5)
lock1.release() #使用Lock创建出的锁默认没有“锁上”
lock1 = Lock()
#创建另外一把锁,并且“锁上”
lock2 = Lock()
lock2.acquire()
#创建另外一把锁,并且“锁上”
lock3 = Lock()
lock3.acquire() t1 = Task1()
t2 = Task2()
t3 = Task3() t1.start()
t2.start()
t3.start()
############生产者与消费者##########
#encoding=utf-8
import threading
import time #python2中
#from Queue import Queue #python3中
from queue import Queue class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
if queue.qsize() < 1000:
for i in range(100):
count = count +1
msg = '生成产品'+str(count)
queue.put(msg)
print(msg)
time.sleep(0.5) class Consumer(threading.Thread):
def run(self):
global queue
while True:
if queue.qsize() > 100:
for i in range(3):
msg = self.name + '消费了 '+queue.get()
print(msg)
time.sleep(1) if __name__ == '__main__':
queue = Queue() for i in range(500):
queue.put('初始产品'+str(i))
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
#########TheadLocal###############
Theadlocal的作用:不用传参数,用一个全局变量能够完成线程里面所有的数据传递,不会因为下一个线程调用该变量而改变该值
import threading # 创建全局ThreadLocal对象:
local_school = threading.local() def process_student():
# 获取当前线程关联的student:
std = local_school.student
print('Hello, %s (in %s)' % (std, threading.current_thread().name)) def process_thread(name):
# 绑定ThreadLocal的student:
local_school.student = name
process_student() t1 = threading.Thread(target= process_thread, args=('dongGe',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('老王',), name='Thread-B')
t1.start()
t2.start()
############异步的实现######################
from multiprocessing import Pool
import time
import os def test():
print("---进程池中的进程---pid=%d,ppid=%d--"%(os.getpid(),os.getppid()))
for i in range(3):
print("----%d---"%i)
time.sleep(1)
return "hahah" def test2(args):
print("---callback func--pid=%d"%os.getpid())
print("---callback func--args=%s"%args) pool = Pool(3)
pool.apply_async(func=test,callback=test2) #异步的理解:主进程正在做某件事情,突然 来了一件更需要立刻去做的事情,
#那么这种,在父进程去做某件事情的时候 并不知道是什么时候去做,的模式 就称为异步
while True:
time.sleep(1)
print("----主进程-pid=%d----"%os.getpid())
python之系统编程 --线程的更多相关文章
- Linux系统编程——线程私有数据
在多线程程序中.常常要用全局变量来实现多个函数间的数据共享.因为数据空间是共享的,因此全局变量也为全部线程共同拥有. 測试代码例如以下: #include <stdio.h> #inclu ...
- Linux系统编程 —线程同步概念
同步概念 同步,指对在一个系统中所发生的事件之间进行协调,在时间上出现一致性与统一化的现象. 但是,对于不同行业,对于同步的理解略有不同.比如:设备同步,是指在两个设备之间规定一个共同的时间参考:数据 ...
- linux服务器开发二(系统编程)--线程相关
线程概念 什么是线程 LWP:Light Weight Process,轻量级的进程,本质仍是进程(在Linux环境下). 进程:独立地址空间,拥有PCB. 线程:也有PCB,但没有独立的地址空间(共 ...
- python之并发编程(线程\进程\协程)
一.进程和线程 1.进程 假如有两个程序A和B,程序A在执行到一半的过程中,需要读取大量的数据输入(I/O操作),而此时CPU只能静静地等待任务A读取完数据才能继续执行,这样就白白浪费了CPU资源.是 ...
- Python之系统编程笔记
概念 命令行工具. Shell 脚本. 系统管理 系统模块 sys 提供一组功能映射Python运行时的操作系统 os 提供跨平台可移植的操作系统编程接口 os.path 提供文件及目 ...
- linux系统编程--线程
安装线程man page,命令:sudo apt-get install manpages-posix-dev 线程概念 什么是线程 LWP:light weight process 轻量级的进程,本 ...
- Linux系统编程 —线程属性
在之前的章节中,我们在调用pthread_create函数创建线程时,第二个参数(即线程属性)都是设为NULL,即使用默认属性.一般情况下,使用默认属性已经可以解决我们开发过程中的大多数问题. 但是, ...
- linux系统编程--线程同步
同步概念 所谓同步,即同时起步,协调一致.不同的对象,对“同步”的理解方式略有不同. 如,设备同步,是指在两个设备之间规定一个共同的时间参考: 数据库同步,是指让两个或多个数据库内容保持一致,或者按需 ...
- python之系统编程 --进程
1.调试(PDB) 代码: [root@master gaoji]# vim test2.py 1 #!/usr/local/bin/python3 2 # -*- coding:utf-8 -*- ...
随机推荐
- android 获取手机设备品牌
在有些数据要获取手机设备是什么品牌,特别做一些适配的时候,好了就讲下怎样或者手机是什么品牌: String brand =android.os.Build.BRAND; 就这么简单!
- caffe---ubuntu1604下anaconda2.5的尝试----失败,建议使用系统的python系统,避免各种各样的陷阱
caffe---ubuntu1604下anaconda2.5的尝试----失败,建议使用系统的python系统,避免各种各样的陷阱. 如果使用caffe+ anacoanda 已经遇到的陷阱有 1. ...
- EntityFramework 6.0 修改一个已经存在的对象
public void UpdateObj(someobject obj) { db.Entry(obj).State = EntityState.Modified; db.SaveChanges() ...
- php 字符串内容是数组格式 转换成数组
一个简单的应用.. 例, $str = "array( 'USD'=>'1', 'GBP'=>'0.6494', 'EUR'=>'0.7668' ,'JPY'= ...
- 【selenium+Python unittest】之使用smtplib发送邮件错误:smtplib.SMTPDataError:(554)、smtplib.SMTPAuthenticationError(例:126邮箱)
原代码如下: import smtplib from email.mime.text import MIMEText from email.header import Header #要发送的服务器 ...
- Gunicorn、Supervisor
简介 Gunicorn来源于Ruby的unicorn项目,是一个Python WSGI HTTP Server,通过pre-fork worker模型来管理和维护worker. 简而言之就是通过多进程 ...
- 【转】cmd chcp命令切换字符格式
cmd chcp命令切换字符格式 命令介绍: chcp 65001 #换成utf-8代码页 chcp 936 #换成默认的gbk chcp 437 #美国英 ...
- TCP交换数据流——Nagle算法简单记录
Nagle算法: 该算法提出的目的是想解决网络中大量的小的TCP数据包造成网络拥塞的问题,举个例子,当客户端要发送一个字节的TCP数据包到服务器时,我们实际上产生了41字节长的分组:包括20字节的IP ...
- getStorageSync const UID = this.$parent.UID wx.getStorageSync('UID')
getStorageSync 在程序运行中是在内存 还是去文件系统读取? const UID = this.$parent.UID wx.getStorageSync('UID') ...
- BZOJ3878: [Ahoi2014&Jsoi2014]奇怪的计算器
BZOJ3878: [Ahoi2014&Jsoi2014]奇怪的计算器 Description [故事背景] JYY有个奇怪的计算器,有一天这个计算器坏了,JYY希望你能帮助他写 一个程序来模 ...