Python 線程和 redis 簡單讀寫操作應用1. python 線程 & 線程池的概念python 中使用線程的兩種方式: 函數或是用類封裝線程對象函數:調h用thread 模組中的start_new_thread()函數產生新線程,thread.start_new_thread(function,args[,kwargs])參數說明:function ---> 線程函數args ---> 傳遞給線程函數的參數,必須是tuple類型kwargs ---> 選擇性參數類方法:使用Threading 模組建立線程,直接從threading.Thread 繼承,然後重寫 __init__ 方法和run 方法和run下面給出兩種方法的簡單實現codes ,在項目上,使用可能更加複雜#!/usr/bin/python# -*- coding:utf-8 -*-import threadimport time#define a function for thread def print_time(threadName ,delay):count = 0while count < 5:time.sleep(delay)count +=1print ("%s: %s " % (threadName,time.ctime(time.time()))# define 2 threadtry:thread.start_new_thread(print_time,("Thread-1",2,))thread.start_new_thread(print_time,("Thread-2",4,))except:print("Error : unable to start thread")while 1 :pass#==============================================#!/usr/bin/python# -*- coding: UTF-8 -*-import threading import timeexitFlag = 0class myThread(threading,Thread): # 繼承父類threading.Threaddef __init__(self ,threadID,name ,counter):threading.Thread.__init__(self)self.threadID=threadIDself.name= nameself.counter = counterdef run(self): # 把要執行的代碼寫到run函數裡面 線程在建立後會直接運行run函數print("starting " + self.name )print_time(self.name ,self.counter,5)print ("Exiting " +self.name)def print_time(threadName,delay ,counter):while counter :if exitFlag:threading.Thread.exit()time.sleep(delay)print("%s : %s" % (threadName,time.ctime(time.time()))counter -=1#create new threadthread1 = myThread(1,"Thread-1",1)thread2= myThread(2,"Thread-2",2)thread1.start()thread2.start()print ("Exiting Main Thread")#==========================================#線程更深入的內容,需要查閱網路( 線程同步,線程優先順序隊列)python 安裝 redispip install redisredis 啟動 redis-server.exe redis.confC:\Users\IBM_ADMIN\Downloads\redis-2.4.5-win32-win64\64bit python 串連 redisr = redis.Redis(host='127.0.0.1',port=6379,db=0)r.set('world','hello')Turer.get('world')# statistics the number of users in read time import timefrom redis import Redisfrom datetime import datetimeONLINE_LAST_MINUTES = 5reids = Redis()p = reids.pipeline()def make_online(user_id): now = int(time.time()) expires = now + ONLINE_LAST_MINUTES * 60 + 10 all_users_key = 'online-users/%d' % (now // 60) user_key = 'user-activity/%s' % user_id print(all_users_key ,user_key) p.sadd(all_users_key,user_id) p.set(user_key,now) p.expireat(all_users_key,expires) p.expireat(user_key,expires) print(p.get(user_key)) print(p.get(all_users_key)) print(p.get(user_key)) #print(expires)make_online('me')make_online('you')#p.execute()想瞭解更多請參考網路 RSHR2.CUST_DIMNSNCGNS_02.USER_CUST_LIST_EXPLDDCGNS_02.USER_CUST_LIST_HDRrunstat 的 目的是 收集最新的統計資訊,方便最佳化器選擇最合適的訪問路徑http://ringcloud.cn.ibm.com/provision/manageCloudringcloud has been deprovision (3)