python import multiprocessing def worker(): pass if __name__ == "__main__": processes = [] for i in range(multiprocessing.cpu_count()): p = multiprocessing.Process(target=worker) processes.append(p) p.start() for p in processes: p.join() python import threading counter = 0 counter_lock = threading.Lock() def increment(): global counter with counter_lock: counter += 1 def worker(): increment() if __name__ == "__main__": threads = [] for i in range(10): t = threading.Thread(target=worker) threads.append(t) t.start() for t in threads: t.join() python import threading import collections queue = collections.deque() queue_lock = threading.Lock() def enqueue(item): with queue_lock: queue.append(item) def dequeue(): with queue_lock: return queue.popleft() def worker(): enqueue("data") if __name__ == "__main__": threads = [] for i in range(10): t = threading.Thread(target=worker) threads.append(t) t.start() for t in threads: t.join()


上一篇:
下一篇:
切换中文