python 多執行緒實現 threading

2021-10-10 11:14:28 字數 1856 閱讀 8846

# encoding: utf-8

#!/usr/bin/python

import threading

import time

import queue

exit =

0class

testthread

(threading.thread)

:def

__init__

(self,

id, name, counter)

: threading.thread.__init__(self)

self.threadid =

id self.name = name

self.counter = counter

# def run(self):

# print("開始" + self.name)

# testtime(self.name, self.counter, 5)

# print("結束" + self.name)

# def testtime(num, delay,counter):

# while counter:

# if exit:

# thread.exit()

# time.sleep(delay)

# print("%s:%s"% (num,time.ctime(time.time())))

# counter -= 1

## thread1 = testthread(1, "執行緒1", 1)

# thread2 = testthread(2, "執行緒2", 2)

## thread1.start()

# thread2.start()

## print("結束多執行緒")

# def run(self):

# print("開始" + self.name)

# threadlock.acquire()

# print_time(self.name,self.counter,3)

# threadlock.release()

## def print_time(threadname, delay, counter):

# while counter:

# time.sleep(delay)

# print ("%s: %s" % (threadname, time.ctime(time.time())))

# counter -= 1

## threadlock = threading.lock()

# threads =

## thread1 = testthread(1, "執行緒1", 1)

# thread2 = testthread(2, "執行緒2", 2)

# thread1.start()

# thread2.start()

## for over in threads:

# over.join()

# print("結束多執行緒")

使用threading模組建立執行緒,直接從threading.thread繼承,然後重寫__init__方法和run方法。

使用thread物件的lock和rlock可以實現簡單的執行緒同步,這兩個物件都有acquire方法和release方法,對於那些需要每次只允許乙個執行緒操作的資料,可以將其操作放到acquire和release方法之間。

python多執行緒實現

資料夾命名不能用官方已有的模組名比如threading.py test.py等等都會報錯 from multiprocessing import process import os 子程序要執行的 def run proc name print run child process s s name,...

python多執行緒實現

coding utf 8 import threading 匯入執行緒模組 from time import ctime,sleep 建立執行緒事件 defeat print 我在吃東西 s ctime 執行緒組 threads 建立執行緒數量 for x in range 10 t1 thread...

python多執行緒執行緒池實現

在python中多執行緒可以使用threading來實現,但實際使用時考慮效能等,大多會使用到執行緒池,下面就是基於python2和python3來說明下執行緒池的使用。import time def testthread fl time.sleep 1 print print fl return ...