码迷,mamicode.com
首页 > 编程语言 > 详细

线程模块练习

时间:2020-04-01 14:47:19      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:star   main   targe   print   getname   模拟   ted   try   started   

1.主线程
import threading
t = threading.current_thread()
print(t) # <_MainThread(MainThread, started 139908235814720)>
print(t.getName()) # MainThread
print(t.ident) # 139908235814720
print(t.isAlive()) # True

2.创建线程
my_thread = threading.Thread()
my_thread = threading.Thread(name=my_thread)
def print_i(i):
    print(打印i:%d%(i,))
my_thread = threading.Thread(target=print_i,args=(1,))
my_thread().start()


3 交替获得CPU时间片
import time
from datetime import datetime
import threading


def print_time():
    for _ in range(5): # 在每个线程中打印5次
        time.sleep(0.1) # 模拟打印前的相关处理逻辑
        print(当前线程%s,打印结束时间为:%s%(threading.current_thread().getName(),datetime.today()))


threads = [threading.Thread(name=t%d%(i,),target=print_time) for i in range(3)]
[t.start() for t in threads]

4.多线程抢夺同一个变量,要加锁
import threading
import time

locka = threading.Lock()
a = 0
def add1():
    global a    
    try:
        locka.acquire() # 获得锁
        tmp = a + 1
        time.sleep(0.2) # 延时0.2秒,模拟写入所需时间
        a = tmp
    finally:
        locka.release() # 释放锁
    print(%s  adds a to 1: %d%(threading.current_thread().getName(),a))
    
threads = [threading.Thread(name=t%d%(i,),target=add1) for i in range(10)]
[t.start() for t in threads]

 

线程模块练习

标签:star   main   targe   print   getname   模拟   ted   try   started   

原文地址:https://www.cnblogs.com/miaoweiye/p/12612209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!