python 多线程 start_new_thread()

一、简述

  CPython实现细节: 由于GIL(Global Interpreter Lock),在CPython中一次只能有一个线程来执行python代码,不过有些面向执行的库可以克服这个限制。如果想要使你的应用程序更好的利用计算机资源的话,最好使用multiprocessing。 但是,如果同时运行多个I/O任务的话,线程依然是一个很好地选择。
  python线程的作用主要是应对I/O任务,例如网络数据的读写等。

二、示例

  1. 函数说明。
  start_new_thread ( function , args [ , kwargs ] )
  创建一个新的线程,返回一个线程标识符。function是线程函数,args是线程函数的参数,是一个list。kwargs可选参数,可不填。

#!/usr/bin/env python

# _*_ coding = utf-8 _*_

import thread
import time

def work_thread(id):

    cnt = 1

    print "Thread %d is runing..." % id

    while True:
        print "Thread with ID %d has counter value %d" % (id, cnt)
        time.sleep(2) 
        cnt += 1


for i in range(1,5):
    thread.start_new_thread(work_thread,(i,))

print "Main thread doing an infinite wait loop..."

while True:
    pass

运行代码,输出结果如下:

$ ./thread_demo.py
Main thread doing an infinite wait loop…
Thread 3 is runing…
Thread 1 is runing…
Thread 2 is runing…
Thread 4 is runing…
Thread with ID 1 has counter value 1
Thread with ID 4 has counter value 1
Thread with ID 2 has counter value 1
Thread with ID 3 has counter value 1
Thread with ID 2 has counter value 2
Thread with ID 3 has counter value 2
Thread with ID 4 has counter value 2
Thread with ID 1 has counter value 2
Thread with ID 3 has counter value 3
Thread with ID 4 has counter value 3
Thread with ID 1 has counter value 3
Thread with ID 2 has counter value 3
Thread with ID 1 has counter value 4
Thread with ID 4 has counter value 4
Thread with ID 2 has counter value 4
Thread with ID 3 has counter value 4

线程退出函数:
thread.exit ()。结束当前线程。调用该函数会触发 SystemExit 异常,如果没有处理该异常,线程将结束。

你可能感兴趣的:(多线程,python)