《Python语言程序设计》王恺 王志 机械工业出版社 第八章 多线程与多进程 课后习题答案


8.5课后习题
(1) 线程是操作系统进行运算调度的最小单位。

(2)当一个进程被创建时,操作系统会自动为进程建立一个线程,通常称为主线程 。

(3) 进程是一个正在执行中的应用程序所有资源的集合。

(4)使用创建线程来执行一个函数,可以不中断当前函数的执行,实现多个函数并 行执行,提高程序的执行效率。

(5)将一个线程的daemon属性设置为 True,则该线程为守护线程。

(6)一个锁在 locked 和 unlocked 两种状态间切换,刚创建的 Lock 对象默认是 unlocked 状态。

(7)多线程同步时如果一个资源对应着多个锁,可能会发生死锁问题,在使用多个 锁时要认真检查。

(8)在 Python 中进行多线程编程,通常使用的高层次多线程编程模块是( B )

         A. thread            B. threading            C. multithread           D. multithreading

(9)threading 模块中用于判断线程是否活动的方法是( D )

         A. start               B. isStart                 C. alive                      D. isAlive

(10)在 Python 中进行多进程编程,通常使用的编程模块是( D )

         A. process         B. processing          C. multiprocess          D. multiprocessing

(11)写出下面程序的运行结果。

import time, threading
def func(x):
    print("%s 线程正在运行!" % threading.current_thread().name)
    time.sleep(x)
    print("%s 线程运行结束!" % threading.current_thread().name)
if __name__ == "__main__":
    print("%s 线程正在运行!" % threading.current_thread().name)
    t_1 = threading.Thread(target=func, args=(5,))
    t_2 = threading.Thread(target=func, args=(3,))
    t_1.start()
    t_2.start()
 
 
#输出结果
MainThread 线程正在运行!
Thread-1 线程正在运行!
Thread-2 线程正在运行!
Thread-2 线程运行结束!
Thread-1 线程运行结束!
(12)下面代码自定义了线程类 my_thread,请将程序填写完整。

import time, threading
class my_thread(threading.Thread):
    def __init__(self, x):
        threading.Thread.__init__ (self)
        self.x = x
    def run(self):
        print("%s 线程正在运行!" % \
              threading.current_thread().name)
        time.sleep(self.x)
        print("%s 线程运行结束!" % threading.current_thread().name)
 

猜你喜欢

转载自blog.csdn.net/weixin_49647262/article/details/122028368