面试题答案
一键面试分析
- 资源竞争:在多线程场景下,如果多个线程访问和修改共享资源(如文件句柄),可能会出现资源竞争问题。当一个线程使用
continue
跳过部分操作时,可能会影响其他线程对共享资源的访问顺序和状态。例如,多个线程同时读取同一个文件,continue
可能导致某个线程跳过一些行,使得其他线程读到的数据顺序与预期不符。 在异步编程(asyncio
)中,虽然不存在线程间资源竞争问题,但如果多个异步任务共享资源(如数据库连接),同样可能出现资源竞争,continue
也可能对资源使用顺序产生影响。 - 任务同步:在多线程中,需要使用锁(
threading.Lock
)等同步机制来确保对共享资源的安全访问。当某个线程执行continue
时,同步机制需要保证在跳过部分操作时不会破坏共享资源的一致性。在异步编程中,asyncio
通过事件循环和async/await
机制来管理任务执行,continue
在异步任务中的使用需要配合await
确保任务间的正确同步。
代码示例
多线程示例
import threading
import time
class FileReaderThread(threading.Thread):
def __init__(self, file_path, lock):
threading.Thread.__init__(self)
self.file_path = file_path
self.lock = lock
def run(self):
with self.lock:
with open(self.file_path, 'r') as file:
for line in file:
if '特定字符串' in line and len(line) > 10:
continue
print(f"线程 {threading.current_thread().name} 处理行: {line.strip()}")
time.sleep(0.1) # 模拟处理时间
file_path = 'test.txt'
lock = threading.Lock()
threads = []
for _ in range(3):
thread = FileReaderThread(file_path, lock)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
异步编程示例
import asyncio
async def read_file(file_path):
async with aiofiles.open(file_path, 'r') as file:
async for line in file:
if '特定字符串' in line and len(line) > 10:
continue
print(f"异步任务处理行: {line.strip()}")
await asyncio.sleep(0.1) # 模拟处理时间
async def main():
tasks = []
file_path = 'test.txt'
for _ in range(3):
task = asyncio.create_task(read_file(file_path))
tasks.append(task)
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
在上述多线程示例中,通过threading.Lock
确保文件访问的线程安全。在异步示例中,使用aiofiles
实现异步文件读取,并利用asyncio
的事件循环和async/await
机制管理任务同步。