python 執行緒初體驗

2021-10-05 04:02:00 字數 1285 閱讀 2660

import threading

import time

class mythread(threading.thread):

def __init__(self, threadid, name, counter):

threading.thread.__init__(self)

self.threadid = threadid

self.name = name

self.counter = counter

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 = mythread(1, "thread-1", 1)

thread2 = mythread(2, "thread-2", 2)

# 開啟新執行緒

thread1.start()

thread2.start()

# 新增執行緒到執行緒列表

# 等待所有執行緒完成

for t in threads:

t.join()

print("退出主線程")

執行結果:

開啟執行緒: thread-1

開啟執行緒: thread-2

thread-1: fri apr 17 12:37:53 2020

thread-1: fri apr 17 12:37:54 2020

thread-1: fri apr 17 12:37:55 2020

thread-2: fri apr 17 12:37:57 2020

thread-2: fri apr 17 12:37:59 2020

thread-2: fri apr 17 12:38:01 2020

退出主線程

Python 初體驗(六)

import random,發現這裡面有很多randomize的method,這裡不再一一贅述,可以通過幫助文件自習看,包括choice,shuffle都是整合度很高的randomize方法 於是嘗試了乙個這樣乙個task,輸入字串長度,輸出乙個隨機產生的字串。鞏固了一下異常的相關處理方法。join...

python函式初體驗

形式引數 被指定具體的值 預設引數,實際引數是呼叫時候的實際指定引數 我們把函式 的引數叫形式函式,函式實際調 的時候,賦予的引數叫實際函式 定義函式的時候,指定形式引數具體的值,這樣的引數叫預設引數 動態引數 動態引數可以解決形式引數 個數 型別 不確定的時候,在動態引數裡,代表元組,代表字典。當...

Linux多執行緒程式設計初體驗

直接上 include pthread.h 執行緒庫,執行緒不是通過核心實現的 include stdio.h include stdlib.h include unistd.h void thread func void arg int main sleep 1 等待1 s,否則程序先結束那麼執行...