python中的多執行緒實現獲取地理位置

2021-09-10 02:56:15 字數 1091 閱讀 6378

# 1. 簡單的爬蟲:

import threading

import time

from urllib.request import urlopen

def timeit(f):

start_time = time.time()

res = f(*args, **kwargs)

end_time = time.time()

return res

class mythread(threading.thread):

def __init__(self, ip):

super(mythread, self).__init__()

self.ip = ip

def run(self):

url = "" % (self.ip)

urlobj = urlopen(url)

# 服務端返回的頁面資訊, 此處為字串型別

pagecontent = urlobj.read().decode('utf-8')

# 2. 處理json資料

import json

# 解碼: 將json資料格式解碼為python可以識別的物件;

dict_data = json.loads(pagecontent)

print("""

%s所在城市: %s

所在國家: %s

""" % (self.ip, dict_data['city'], dict_data['country']))

@timeit

def main():

ips = ['12.13.14.%s' % (i + 1) for i in range(1000)]

threads =

# 執行緒在建立和銷毀過程中需要耗費資源和時間;

for ip in ips:

t = mythread(ip)

t.start()

[thread.join() for thread in threads]

if __name__ == '__main__':

main()

python中多執行緒同步實現

import threading import time python 實現執行緒同步 event r lock semaphore barricade condition event 使用 e.set e.clear e.is set e.wait def event usage 主要就set設定...

python 多執行緒的實現

併發 多個任務同一時間段進行 並行 多個任務同一時刻進行 執行緒模組 python通過兩個標準庫 thread 和threading,提供對執行緒的支援 threading對 thread進行了封裝 因此在實際的使用中我們一般都是使用threading,threading模組中提供了thread l...

python中多執行緒 Python之多執行緒

python之多執行緒 一 概念 1 多工可以由多程序完成,也可以由乙個程序內的多執行緒完成。程序是由若干的執行緒組成,乙個程序至少有乙個程序。執行緒是作業系統直接支援的執行單元,天賜高階預壓通常都是內建多執行緒的支援,python的執行緒是真正的posix thread而不是模擬出來的執行緒。2 ...