已有183人关注
实战任务1 实现不了手机号码滚动
发表在Python图书答疑 2018-11-10 《Python从入门到项目实践》第16章 进程和线程 259页-0页
是否精华
版块置顶:
from threading import Thread,Lock
import random
import linecache

def task(filename):
    mutex.acquire()  # 上锁
    phone = get_phone(filename)  # 获取手机号
    print('中奖手机号是: %s' % (phone,))
    mutex.release()  # 释放锁

def get_phone(filename):
    '''获取手机号'''
    count = len(linecache.getlines(filename))
    num = random.randint(1, count)
    phone = linecache.getline(filename,num)
    removeLine(filename, num-1)
    return phone

def removeLine(filename, lineno):
    '''
    删除文件中的指定行
    :param filename: 文件名
    :param lineno: 行号
    :return:
    '''
    fro = open(filename, "r",encoding='UTF-8')
    current_line = 0
    while current_line < lineno:
        fro.readline()
        current_line += 1

    seekpoint = fro.tell()
    frw = open(filename, "r+")
    frw.seek(seekpoint, 0)

    # read the line we want to discard
    fro.readline()  # 读入一行进内存 ,同时 文件指针下移实现删除

    # now move the rest of the lines in the file
    # one line back
    chars = fro.readline()
    while chars:
        frw.writelines(chars)
        chars = fro.readline()
    fro.close()
    frw.truncate()
    frw.close()

if __name__ == "__main__":
    filename = 'phone.txt'
    mutex = Lock() # 设置锁
    t_l = []
    for i in range(3):
        t = Thread(target=get_phone,args=(filename,)) # 创建线程
        t_l.append(t) # 写入列表
        t.start()     # 开启线程
    for t in t_l:
        t.join()   # 等待子线程结束
分享到:
精彩评论 1
无脸大叔_1538205275
学分:318 LV5
2018-11-18
沙发

老师老师你在哪了

首页上一页 1 下一页尾页 1 条记录 1/1页
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照