Python之多线程编程

第1关 线程同步之报数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 本关将根据测试输入创建多个线程,每个线程相当于队列中的一个人,他们报的数用全局变量x存储;
# 学员需要编写run()方法,使得每个线程将自己该报的数输出;
# 注意在输出语句之前,加入time.sleep(0.1)防止输出过快造成顺序混乱的情况。
# -*- coding: utf-8 -*-
import threading
import time
lock = threading.Lock()


class mythread(threading.Thread):
    x = 0

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global x
    # *********begin*********#
        lock.acquire()
        x += 1
        print(x,end='')
        time.sleep(0.1)
        lock.release()

    # ********* end*********#
num = input()
t1 = []
for i in range(int(num)):
    t = mythread()
    t1.append(t)
x = 0
for i in t1:
    i.start()

第2关 线程同步之生产者-消费者问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# -*- coding: utf-8 -*-

import threading
import time
con = threading.Condition()
class Producer(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num
    def run(self):
        global x
        #*********begin*********#
        with con:
            while x >= self.num:
                con.wait()
            for i in range(x, self.num+1):
                if(i!=self.num):
                    print(i, end=" ")
                else:
                    print(i)
                x += 1
                time.sleep(0.1)
            con.notify()
        #********* end*********#
class Consumer(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num
    def run(self):
        global x
        #*********begin*********#
        with con:
            while x <= 0:
                con.wait()
            for i in range(self.num,-1, -1):
                if(i!=-1):
                    print(i, end=" ")
                else:
                    print(i)
                x -= 1
                time.sleep(0.1)
            con.notify_all()
        #********* end*********#
num = input()
x = 0
num = int(num)
p = Producer(num)
c = Consumer(num)
p.start()
c.start()
p.join()
c.join()

Python–进程和线程

第1关 Python多进程-求素数个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import math

from multiprocessing import cpu_count

from multiprocessing import Pool



# 判断数字是否为质数

# ********** Begin *********#




def isPrime(n):

    if n < 2:

        return False

    for i in range(2, int(math.sqrt(n)) + 1):

        if n % i == 0:

            return False

    return True




# ********** End *********#



# 计算给定区间含有多少个质数

# ********** Begin *********#
def howMany(T):
    count = 0
    for i in range(T[0], T[1]):
        if isPrime(i):
            count += 1
    return count
# ********** End *********#



# 对整个数字空间N进行分段CPU_COUNT

# ********** Begin *********#
def separateNum(N, CPU_COUNT):
    sepList = []
    for i in range(CPU_COUNT):
        sepList.append([int(N / CPU_COUNT * i), int(N / CPU_COUNT * (i + 1))])
    return sepList

# ********** End *********#
if __name__ == '__main__':
    N = int(input())
    # 多进程
    CPU_COUNT = cpu_count()  # CPU内核数 本机为8
    pool = Pool(CPU_COUNT)
    sepList = separateNum(N, CPU_COUNT)
    result = []
    for i in range(CPU_COUNT):
        result.append(pool.apply_async(howMany, (sepList[i], )))
    pool.close()
    pool.join()
    ans = 0
    list = [res.get() for res in result]
    print(sum(list), end='')

第2关 Python多线程-求合数个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import threading
import math
ans = 0
lock = threading.Lock()
# 判断数字是否为质数

#********** Begin *********#
def isPrime(n):
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True
#********** End *********#

#********** Begin *********#

# 计算给定区间含有多少个质数
def howMany(T):
    sum = 0;
    for i in range(T[0], T[1] + 1):
        if isPrime(i):
            sum += 1
    lock.acquire()
    try:
        global ans
        ans += sum
    finally:
        lock.release()
#********** End *********#

#********** Begin *********#

# 对整个数字空间N进行分段CPU_COUNT
def seprateNum(N, CPU_COUNT):
    list = [[i * (N // CPU_COUNT) + 1, (i + 1) * (N // CPU_COUNT)] for i in range(0, CPU_COUNT)]
    list[0][0] = 1
    if list[CPU_COUNT - 1][1] < N:
        list[CPU_COUNT - 1][1] = N
    return list
#********** End *********#

if __name__ == '__main__':
    N = int(input())
    threadNum = 32
    t = []
    sepList = seprateNum(N, threadNum)
    for i in range(0, threadNum):
        t.append(threading.Thread(target = howMany, args = (sepList[i], )))
        t[i].start()
    for i in range(0, threadNum):
        t[i].join()
    print(N - 1 - ans, end = '')

第3关 Python-ThreadLocal变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import threading

x = 10
data = threading.local()

def action():
    global x
    data.num = x
    for i in range(1000000):
        data.num += 1
        data.num -= 1
    x = data.num

x = int(input())
thread = []
for i in range(10):
    thread.append(threading.Thread(target = action))
    thread[i].start()
for i in range(10):
    thread[i].join()
print(x)

第4关 Python-进程 VS 线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import math
from multiprocessing import cpu_count
from multiprocessing import Pool
N = int(input())
a = list(map(int, input().split(' ')))
def howMany(T):
    ans = 0
    for i in range(T[0] - 1, T[1]):
        ans = max(ans, a[i])
    return ans
# 对整个数字空间N进行分段CPU_COUNT

def seprateNum(N, CPU_COUNT):
    list = [[i * (N // CPU_COUNT) + 1, (i + 1) * (N // CPU_COUNT)]
            for i in range(0, CPU_COUNT)]
    list[0][0] = 1
    if list[CPU_COUNT - 1][1] < N:
        list[CPU_COUNT - 1][1] = N
    return list

if __name__ == '__main__':
    # 使用多线程或者多进程,求一个整数数组里的最大值
    # ********** Begin *********#
    CPU_COUNT = cpu_count()  
    pool = Pool(CPU_COUNT)
    sepList = seprateNum(N, CPU_COUNT)
    result = []
    for i in range(CPU_COUNT):
        result.append(pool.apply_async(howMany, (sepList[i], )))
    pool.close()
    pool.join()
    ans = 0
    list = [res.get() for res in result]
    print(max(list))

# ********** End *********#

第5关 Python-分布式进程

  1. 用 Python 实现分布式程序,一般用Python里面哪个类?
    Process