• python学习之多线程(一)


    引入线程包或者命名空间import threading

    一:建立一个简单的线程程序

    import time, threading

    def test():
        print('thread %s is running...' % threading.current_thread().name)
        n = 0
        while n < 5:
            n = n + 1
            print('thread %s >>> %s' % (threading.current_thread().name, n))
            time.sleep(1)
        print('thread %s ended.' % threading.current_thread().name)

    print('thread %s is running...' % threading.current_thread().name)
    t = threading.Thread(target=test, name='test')
    t.start()
    t.join()
    print('thread %s ended.' % threading.current_thread().name)

    运行结果如下:

    二:多个线程中线程同步

    #-*- encoding: gb2312 -*-
    import string, threading, time
     
    def thread_main(a):
      global count, mutex
      # 获得线程名
      threadname = threading.currentThread().getName()
     
      for x in xrange(0, int(a)):
        # 取得锁
        mutex.acquire()
        count = count + 1
        # 释放锁
        mutex.release()
        print(threadname, x, count)
        time.sleep(1)
     
    def main(num):
      global count, mutex
      threads = []
     
      count = 1
      # 创建一个锁
      mutex = threading.Lock()
      # 先创建线程对象
      for x in xrange(0, num):
        threads.append(threading.Thread(target=thread_main, args=(10,)))
      # 启动所有线程
      for t in threads:
        t.start()
      # 主线程中等待所有子线程退出
      for t in threads:
        t.join()
     
    if __name__ == '__main__':
      num = 4
      # 创建4个线程
      main(4)

    相关理解:

    如何理解join()方法:使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数, 通俗一点说就是让当前操作join方法的线程先完成,再去执行其它流程,timeout是超时时间,比如join(1),如果过了1s线程没有结束,线程会自动结束

    如何理解线程同步:当系统中对同一个变量或方法同一时刻只允许被一个动作占用时,就要采用线程同步的方案去处理了

  • 相关阅读:
    PHP写一段代码,确保多个进程同时写入一个文件成功
    PHP中的中文截取乱码问题_gb2312_utf-8
    TortoiseSVN使用详细步骤
    限制页面内部链接访问源-HTML注释
    Redis配置文件解读
    window下部署php_redis扩展
    js延迟加载,提升网页加载速度
    HTML5 LocalStorage 本地存储
    静态HTML页面不缓存js文件的方法
    寻找幸运数
  • 原文地址:https://www.cnblogs.com/airven/p/4991608.html
Copyright © 2020-2023  润新知