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线程没有结束,线程会自动结束

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

原文地址:https://www.cnblogs.com/airven/p/4991608.html