GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — 添加多线程例子,来自chatgpt · feixiao/learning-python@c1c807a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • multithread
    • main.py
    • test.txt
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎multithread/main.py‎

Copy file name to clipboard
+46-21Lines changed: 46 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,55 @@
1-
import concurrent.futures
2-
import random
3-
import time
1+
import threading
42

5-
# 线程处理函数
63

4+
# 下面是一个简单的Python程序,它使用多线程来分析和处理文本文件。程序将文本文件分成N段,每段由一个线程处理,线程会查找指定的关键字并返回关键字所在的行数。
5+
# 最后,主线程将所有线程的结果合并。
76

8-
def worker(thread_id):
9-
# 模拟线程的处理过程
10-
result = f"Thread {thread_id} processed data: {random.randint(1, 100)}"
7+
# 这个函数接受一个文本段落和一个关键字作为参数,然后在段落中查找关键字,返回包含关键字的行号列表。
8+
def process_segment(segment, keyword):
9+
result = []
10+
lines = segment.split('\n')
11+
for i, line in enumerate(lines, start=1):
12+
if keyword in line:
13+
result.append(i)
14+
return result
1115

12-
# 模拟处理时间
13-
time.sleep(2)
16+
# 这个函数接受文件名、线程数量和关键字作为参数。首先,它读取文件内容,然后将文件内容分成N段,其中N是线程数量。接下来,它创建一个线程池,每个线程处理一个文本段,并调用process_segment函数来查找关键字。最后,主线程等待所有线程完成,并将结果合并后返回。
1417

15-
return result
18+
19+
def analyze_file(filename, num_threads, keyword):
20+
with open(filename, 'r') as file:
21+
content = file.read()
22+
23+
segment_size = len(content) // num_threads
24+
segments = [content[i:i+segment_size]
25+
for i in range(0, len(content), segment_size)]
26+
27+
threads = []
28+
results = []
29+
30+
def worker(segment):
31+
result = process_segment(segment, keyword)
32+
results.extend(result)
33+
34+
for segment in segments:
35+
thread = threading.Thread(target=worker, args=(segment,))
36+
threads.append(thread)
37+
thread.start()
38+
39+
for thread in threads:
40+
thread.join()
41+
42+
# 对结果进行排序
43+
results.sort()
44+
return results
1645

1746

18-
# 创建ThreadPoolExecutor线程池
19-
with concurrent.futures.ThreadPoolExecutor() as executor:
20-
# 提交线程任务
21-
thread_futures = [executor.submit(worker, i) for i in range(5)]
47+
if __name__ == "__main__":
48+
filename = input("请输入文件名:")
49+
num_threads = int(input("请输入线程数:"))
50+
keyword = input("请输入要查找的关键字:")
2251

23-
# 等待所有线程完成,并获取结果
24-
results = list(concurrent.futures.as_completed(thread_futures))
52+
results = analyze_file(filename, num_threads, keyword)
2553

26-
# 主线程按照提交的顺序获取处理结果
27-
print("Main thread collecting results:")
28-
for future in thread_futures:
29-
result = future.result()
30-
print(result)
54+
print(f"关键字'{keyword}'出现在以下行数:")
55+
print(results)
Collapse file

‎multithread/test.txt‎

Copy file name to clipboard
+51Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import threading
2+
3+
4+
# 下面是一个简单的Python程序,它使用多线程来分析和处理文本文件。程序将文本文件分成N段,每段由一个线程处理,线程会查找指定的关键字并返回关键字所在的行数。
5+
# 最后,主线程将所有线程的结果合并。
6+
7+
# 这个函数接受一个文本段落和一个关键字作为参数,然后在段落中查找关键字,返回包含关键字的行号列表。
8+
def process_segment(segment, keyword):
9+
result = []
10+
lines = segment.split('\n')
11+
for i, line in enumerate(lines, start=1):
12+
if keyword in line:
13+
result.append(i)
14+
return result
15+
16+
# 这个函数接受文件名、线程数量和关键字作为参数。首先,它读取文件内容,然后将文件内容分成N段,其中N是线程数量。接下来,它创建一个线程池,每个线程处理一个文本段,并调用process_segment函数来查找关键字。最后,主线程等待所有线程完成,并将结果合并后返回。
17+
def analyze_file(filename, num_threads, keyword):
18+
with open(filename, 'r') as file:
19+
content = file.read()
20+
21+
segment_size = len(content) // num_threads
22+
segments = [content[i:i+segment_size]
23+
for i in range(0, len(content), segment_size)]
24+
25+
threads = []
26+
results = []
27+
28+
def worker(segment):
29+
result = process_segment(segment, keyword)
30+
results.extend(result)
31+
32+
for segment in segments:
33+
thread = threading.Thread(target=worker, args=(segment,))
34+
threads.append(thread)
35+
thread.start()
36+
37+
for thread in threads:
38+
thread.join()
39+
40+
return results
41+
42+
43+
if __name__ == "__main__":
44+
filename = input("请输入文件名:")
45+
num_threads = int(input("请输入线程数:"))
46+
keyword = input("请输入要查找的关键字:")
47+
48+
results = analyze_file(filename, num_threads, keyword)
49+
50+
print(f"关键字'{keyword}'出现在以下行数:")
51+
print(results)

0 commit comments

Comments
0 (0)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.