Python 基本语法学习-2

Python学习之路,记录基本的语法学习。

pickle的用法

# pickle save and get history
import pickle
# use pickle command to write
##a_dict = {'da':111, 2:[23, 1, 23], '32':{1:2, 'd':'sad'}}
##file = open('pickle_example.pickle', 'wb')
##pickle.dump(a_dict, file)
##file.close()

# get history
with open('pickle_example.pickle', 'rb') as file:
    a_dict1 = pickle.load(file)
print(a_dict1)

dump将一个词典写入到文件中,load从词典中家在这些数据。

说明:有用的用法 with open() as file

set的用法

# set
char_list = ['a', 'b', 'c', 'd', 'd']
sentence = 'welcome Back to this tutorial'
print(set(char_list))
print(type(set(char_list)))

print('sentence:', set(sentence))

unique_char = set(char_list)
unique_char.add('e')
print('add:', unique_char)
unique_char.remove('b')
print('remove:', unique_char)
unique_char.discard('y')
print('discard:', unique_char)

char_list_2 = {'3', '43', '23', 'd'}
print('difference:', unique_char.difference(char_list_2))
print('intersection:', unique_char.intersection(char_list_2))

set方法是从列表中去除相同的字符

说明:type()显示方法返回数据的基本类型,char的基本操作 add() 添加 remove() 移除已存在列表中的字符,discard() 移除字符串中一个未知的字符 difference() 找到和列表中不相同的数据集 intersection() 插入数据集

thread使用说明

# threading added_thread
import threading

def thread_job():
    print('this is an added threawd, number is %s'%threading.current_thread)
    for i in range(1, 20, 2):
        print('current i:', i)

def main():
    added_thread = threading.Thread(target=thread_job)
    added_thread.start()
    print(threading.active_count())
    print(threading.enumerate())
    print(threading.current_thread())

if __name__ == '__main__':
    main()

多线程是在一个进程中为了资源能够有效地利用所采用的一种策略。

说明:thread有start() join()防止进程中断线程,active_count() emuerate()当前线程数量 Thread() target线程使用方法。

多线程使用

扫描二维码关注公众号,回复: 2453635 查看本文章

# threading added_thread
import threading
import time

def thread_job(a, b):
    print('this is an added threawd, number is %s'%threading.current_thread)
    for i in range(a, b, 2):
        print('\ncurrent i:', i)
        time.sleep(0.1)

def main():
    added_thread = threading.Thread(target=thread_job, name='T1', args=(2, 6))
    added_thread_2 = threading.Thread(target=thread_job, name='T2', args=(1, 10))
    added_thread.start()
    added_thread_2.start()
    
    added_thread.join()
    added_thread_2.join()
    print('all done\n')
    print(threading.active_count())
    print(threading.enumerate())
    print(threading.current_thread())

if __name__ == '__main__':
    main()

多线程使用是通过start()和join()来使用的。线程中可以采取线程锁的方式来抢占资源。

说明:线程锁Lock()方法  lock中采用了acqurie()和release()来加锁和释放锁。

线程队列使用

import threading
import time
from queue import Queue

def job(l, q):
    for i in range(len(l)):
        l[i] = l[i]**2
    q.put(l)

def multithreading():
    q = Queue()
    threads = []
    data = [[2, 3, 4], [2, 45, 5], [32, 3, 4], [233, 42, 12]]
    for i in range(4):
        t = threading.Thread(target=job, args=(data[i], q))
        t.start()
        threads.append(t)
    for thread in threads:
        thread.join()
    result = []
    for _ in range(4):
        result.append(q.get())
    print(result)
if __name__ == '__main__':
    multithreading()

线程队列需要导入一个queue的Queue包,from queue import Queue

说明:队列中需要使用put()和get()方法,append()是增加的方法

线程锁的使用

import threading

def job1():
    global A, lock
    lock.acquire()
    for i in range(10):
        A += i
        print('job1:', A)
    lock.release()
def job2():
    global A, lock
    lock.acquire()
    for i in range(10):
        A += 5
        print('job2:', A)
    lock.release()
if __name__ == '__main__':
    A = 0
    lock = threading.Lock()
    t1 = threading.Thread(target=job1)
    t2 = threading.Thread(target=job2)
    t1.start()
    t2.start()
    t1.join()
    t2.join()
线程锁是将加入队列中的县城进行资源锁定的一个操作,一般资源锁是通过在main方法中定义好,在函数中通过形参或者使用global方式进行使用的。

多进程使用multiprocessing

# multi process
import multiprocessing as mp

def job2(l, q):
    print('process job')
    q.put(l)
    

if __name__ == '__main__':
    q = mp.Queue()
    p1 = mp.Process(target=job2, args=(1, q))
    p2 = mp.Process(target=job2, args=(2, q))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print('processing 1')
    res1 = q.get();
    res2 = q.get();
    print(res1+res2)
多进程和多线程使用方法是一样的,通过Process()创建一个,start()开始和join()加入队列中。最后在函数形参中通过传递参数来实现操作。

说明:多进程中也有队列操作,通过put()和get()方法来实现的。

多核操作multicore

# multiprocessing pool
import multiprocessing as mp

def job(x):
    return x*x

def multicore():
    pool = mp.Pool(processes = 2)
    res = pool.map(job, range(10))
    print(res)

    res = pool.apply_async(job, (2,))
    print(res.get())

    multi_res = [pool.apply_async(job, (i,)) for i in range(10)]
    print([res.get() for res in multi_res])

if __name__ == '__main__':
    multicore()
线程池pool概念,将所有进程通过一个pool简单有效的使用。

说明:multicore concept,多进程中添加一个pool(processes处理器数量),通过map操作可以实现多进程处理,很简单也很有效。apply_async只能单次使用。

共享内存share memory

# multi process memory



value = mp.Value('i', 1) # i
array = mp.Array('i', [1, 2, 5, 6])

多核的概念是在多个cpu中通过公共资源cache进行数据交换。

说明:在多进程中,multiprocessing中有Value(‘type’, value)的函数,也有Array('type', value)

多核锁概念

# multiprocessing global variable
import multiprocessing as mp
import time
def job(x, i, l):

    l.acquire()
    for _ in range(10):
        time.sleep(0.1)
        x.value = x.value+i
        print('x:', x.value)
    l.release()

if __name__ == '__main__':
    l = mp.Lock()
    x = mp.Value('i', 10)
    mp1 = mp.Process(target=job, args=(x, 3, l))
    mp2 = mp.Process(target=job, args=(x, 1, l))
    mp1.start()
    mp2.start()
    mp1.join()
    mp2.join()
    print('main process:', x.value)
多进程和多线程一样通过multiprocessing中Lock()操作,实现进程锁的操作。

猜你喜欢

转载自blog.csdn.net/u011687724/article/details/78620730