python防遗忘复习练手之:多线程

多线程

#coding=utf8

import threading
import time

def test(p):
    time.sleep(0.1)
    print(p)

a = threading.Thread(target=test,args=[1])
b = threading.Thread(target=test,args=[1])
a.start()
b.start()

a.join()
b.join()

ts = []

for i in range(0,15):
    th = threading.Thread(target=test,args=[i])
    ts.append(th)

for i in ts:
    i.start()
    i.join()


mlock = threading.Lock()

num = 0

def change_num():
    global num

    mlock.acquire()
    try:
        num = num + 1
        print("num = " + str(num))
    finally:
        # pass
        mlock.release()


for x in range(1,10):
    t = threading.Thread(target=change_num)
    t.start()
    t.join()

print("***********************")

线程同步

# coding=utf8
import threading

mylock = threading.RLock()
num = 0


class myThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self, name=name)

    def run(self):
        global num
        while True:
            mylock.acquire()
            print '%s locked,Number : %d' % (threading.currentThread().name, num)
            if num >= 4:
                mylock.release()
                print '%s released,Number:%d' % (threading.currentThread().name, num)
                break
            num += 1
            print '%s released,Number:%d' % (threading.currentThread().name, num)
            mylock.release()


if __name__ == '__main__':
    thread1 = myThread('Thread_1')
    thread2 = myThread('Thread_2')
    thread1.start()
    thread2.start()

你可能感兴趣的:(python防遗忘复习练手之:多线程)