{"id":744,"date":"2026-03-26T13:40:00","date_gmt":"2026-03-26T05:40:00","guid":{"rendered":"https:\/\/mitongxue.cn\/?p=744"},"modified":"2026-07-21T14:17:16","modified_gmt":"2026-07-21T06:17:16","slug":"python%e4%b8%ad%e5%a4%9a%e7%ba%bf%e7%a8%8b","status":"publish","type":"post","link":"https:\/\/mitongxue.cn\/index.php\/2026\/03\/26\/python%e4%b8%ad%e5%a4%9a%e7%ba%bf%e7%a8%8b\/","title":{"rendered":"python\u4e2d\u591a\u7ebf\u7a0b"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">threading \u6a21\u5757<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>threading<\/code> \u662f Python \u6807\u51c6\u5e93\u4e2d\u7528\u4e8e\u591a\u7ebf\u7a0b\u7f16\u7a0b\u7684\u6a21\u5757\u3002<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">\u521b\u5efa\u7ebf\u7a0b<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>def worker(name: str, duration: int):<br> &nbsp; &nbsp;print(f\"\u7ebf\u7a0b {name} \u5f00\u59cb\u5de5\u4f5c\")<br> &nbsp; &nbsp;time.sleep(duration)<br> &nbsp; &nbsp;print(f\"\u7ebf\u7a0b {name} \u5de5\u4f5c\u5b8c\u6210\")<br>\u200b<br>\u200b<br># \u521b\u5efa\u7ebf\u7a0b<br>t = threading.Thread(target=worker, args=(\"A\", 2))<br>t.start() &nbsp;# \u542f\u52a8\u7ebf\u7a0b<br>print(\"\u4e3b\u7ebf\u7a0b\u7ee7\u7eed\u6267\u884c\")<br>t.join() &nbsp;# \u7b49\u5f85\u7ebf\u7a0b\u7ed3\u675f<br>print(\"\u4e3b\u7ebf\u7a0b\u7b49\u5f85\u7ed3\u675f\")<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u8f93\u51fa\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\u7ebf\u7a0b A \u5f00\u59cb\u5de5\u4f5c<br>\u4e3b\u7ebf\u7a0b\u7ee7\u7eed\u6267\u884c<br>...<br>\u7ebf\u7a0b A \u5de5\u4f5c\u5b8c\u6210<br>\u4e3b\u7ebf\u7a0b\u7b49\u5f85\u7ed3\u675f<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">\u7ee7\u627f Thread \u7c7b<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>\u5b9a\u4e49\u5b50\u7c7b<\/strong>\uff1a\u521b\u5efa\u4e00\u4e2a\u7c7b\uff0c\u5e76\u7ee7\u627f <code>threading.Thread<\/code>\u3002<\/li>\n\n\n\n<li><strong>\u91cd\u5199 init \u65b9\u6cd5<\/strong>\uff1a\u5728\u521d\u59cb\u5316\u65b9\u6cd5\u4e2d\uff0c<strong>\u5fc5\u987b<\/strong>\u8c03\u7528 <code>super().__init__()<\/code> \u4ee5\u786e\u4fdd\u7ebf\u7a0b\u5bf9\u8c61\u88ab\u6b63\u786e\u521d\u59cb\u5316\u3002\u4f60\u53ef\u4ee5\u5728\u8fd9\u91cc\u63a5\u6536\u5e76\u4fdd\u5b58\u81ea\u5b9a\u4e49\u53c2\u6570\u3002<\/li>\n\n\n\n<li><strong>\u91cd\u5199 run \u65b9\u6cd5<\/strong>\uff1a\u5c06\u7ebf\u7a0b\u9700\u8981\u6267\u884c\u7684\u4e1a\u52a1\u903b\u8f91\u4ee3\u7801\u7f16\u5199\u5728 <code>run()<\/code> \u65b9\u6cd5\u5185\u3002\u5f53\u7ebf\u7a0b\u542f\u52a8\u65f6\uff0c\u4f1a\u81ea\u52a8\u6267\u884c\u8fd9\u91cc\u7684\u4ee3\u7801\u3002<\/li>\n\n\n\n<li><strong>\u542f\u52a8\u7ebf\u7a0b<\/strong>\uff1a\u5b9e\u4f8b\u5316\u81ea\u5b9a\u4e49\u7684\u7ebf\u7a0b\u7c7b\uff0c\u5e76\u8c03\u7528 <code>start()<\/code> \u65b9\u6cd5\u542f\u52a8\u7ebf\u7a0b\u3002<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>class MyThread(threading.Thread):\n\u00a0 def __init__(self, name, delay):\n\u00a0 \u00a0 \u00a0 super().__init__() # \u5fc5\u987b\u8c03\u7528\u7236\u7c7b\u6784\u9020\u51fd\u6570\n\u00a0 \u00a0 \u00a0 self.name = name\n\u00a0 \u00a0 \u00a0 self.delay = delay\n\u200b\n\u00a0 def run(self):\n\u00a0 \u00a0 \u00a0 # \u7ebf\u7a0b\u6267\u884c\u7684\u6838\u5fc3\u903b\u8f91\n\u00a0 \u00a0 \u00a0 print(f\"\u7ebf\u7a0b\u3010{self.name}\u3011\u542f\u52a8\")\n\u00a0 \u00a0 \u00a0 time.sleep(self.delay) # \u6a21\u62df\u8017\u65f6\u64cd\u4f5c\n\u00a0 \u00a0 \u00a0 print(f\"\u7ebf\u7a0b\u3010{self.name}\u3011\u7ed3\u675f\")\n\u200b\nif __name__ == \"__main__\":\n\u00a0 # \u521b\u5efa\u81ea\u5b9a\u4e49\u7ebf\u7a0b\u5bf9\u8c61\n\u00a0 t1 = MyThread(\"\u7ebf\u7a0b-1\", 2)\n\u00a0 t2 = MyThread(\"\u7ebf\u7a0b-2\", 1)\n\u200b\n\u00a0 # \u542f\u52a8\u7ebf\u7a0b\uff08\u4f1a\u81ea\u52a8\u8c03\u7528 run \u65b9\u6cd5\uff09\n\u00a0 t1.start()\n\u00a0 t2.start()\n\u200b\n\u00a0 # \u963b\u585e\u4e3b\u7ebf\u7a0b\uff0c\u7b49\u5f85\u5b50\u7ebf\u7a0b\u6267\u884c\u5b8c\u6bd5\n\u00a0 t1.join()\n\u00a0 t2.join()\n\u00a0 print(\"\u6240\u6709\u7ebf\u7a0b\u6267\u884c\u5b8c\u6bd5\")<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\"><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>class WorkerThread(threading.Thread):<br> &nbsp; &nbsp;def __init__(self, name: str, duration: int):<br> &nbsp; &nbsp; &nbsp; &nbsp;super().__init__(name=name)<br> &nbsp; &nbsp; &nbsp; &nbsp;self._duration = duration<br>\u200b<br> &nbsp; &nbsp;def run(self) -&gt; None:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"\u7ebf\u7a0b {self.name} \u5f00\u59cb\uff0c\u53c2\u6570: {self._duration}\")<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(self._duration)<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"\u7ebf\u7a0b {self.name} \u5b8c\u6210\")<br>\u200b<br>\u200b<br>t = WorkerThread(\"B\", 1)<br>t.start()<br>t.join()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">\u5b88\u62a4\u7ebf\u7a0b (Daemon)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u4e3b\u7ebf\u7a0b\u9000\u51fa\u65f6\uff0c<strong>\u975e\u5b88\u62a4\u7ebf\u7a0b<\/strong>\u4f1a\u963b\u6b62\u8fdb\u7a0b\u9000\u51fa\uff0c<strong>\u5b88\u62a4\u7ebf\u7a0b<\/strong>\u4f1a\u88ab\u5f3a\u5236\u7ec8\u6b62\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>def worker():<br> &nbsp;  print(\"\u975e\u5b88\u62a4\u7ebf\u7a0b\uff1a\u5f00\u59cb\u5e72\u6d3b...\")<br> &nbsp;  time.sleep(3)  # \u6a21\u62df\u8017\u65f6 3 \u79d2\u7684\u5de5\u4f5c<br> &nbsp;  print(\"\u975e\u5b88\u62a4\u7ebf\u7a0b\uff1a\u5e72\u5b8c\u4e86\uff01\")<br>\u200b<br>t = threading.Thread(target=worker)<br># t.daemon = False  # \u9ed8\u8ba4\u5c31\u662f False\uff0c\u53ef\u4ee5\u4e0d\u5199<br>t.start()<br>\u200b<br>print(\"\u4e3b\u7ebf\u7a0b\uff1a\u6211\u8981\u4e0b\u73ed\u4e86\uff01\")<br># \u4e3b\u7ebf\u7a0b\u7ed3\u675f\uff0c\u4f46\u56e0\u4e3a t \u662f\u975e\u5b88\u62a4\u7ebf\u7a0b\uff0c\u8fdb\u7a0b\u4f1a\u7b49\u5f85 t \u6267\u884c\u5b8c\u6bd5\uff08\u8017\u65f6\u7ea6 3 \u79d2\uff09\u624d\u771f\u6b63\u9000\u51fa\u3002<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>def worker():<br> &nbsp;  print(\"\u5b88\u62a4\u7ebf\u7a0b\uff1a\u5f00\u59cb\u5e72\u6d3b...\")<br> &nbsp;  time.sleep(3)  # \u6a21\u62df\u8017\u65f6 3 \u79d2\u7684\u5de5\u4f5c<br> &nbsp;  print(\"\u5b88\u62a4\u7ebf\u7a0b\uff1a\u5e72\u5b8c\u4e86\uff01\")  # \u8fd9\u884c\u6c38\u8fdc\u4e0d\u4f1a\u88ab\u6253\u5370<br>\u200b<br>t = threading.Thread(target=worker)<br>t.daemon = True  # \u8bbe\u7f6e\u4e3a\u5b88\u62a4\u7ebf\u7a0b<br>t.start()<br>\u200b<br>time.sleep(1) # \u7a0d\u5fae\u7b49\u4e00\u4e0b\uff0c\u786e\u4fdd\u5b50\u7ebf\u7a0b\u6253\u5370\u4e86\u7b2c\u4e00\u53e5\u8bdd<br>print(\"\u4e3b\u7ebf\u7a0b\uff1a\u6211\u8981\u4e0b\u73ed\u4e86\uff01\")<br># \u4e3b\u7ebf\u7a0b\u7ed3\u675f\uff0c\u53d1\u73b0 t \u662f\u5b88\u62a4\u7ebf\u7a0b\uff0c\u76f4\u63a5\u5f3a\u5236\u7ec8\u6b62\u5b83\uff0c\u8fdb\u7a0b\u77ac\u95f4\u9000\u51fa\u3002<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>def daemon_worker():<br> &nbsp; &nbsp;while True:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(\"\u5b88\u62a4\u7ebf\u7a0b\u8fd0\u884c\u4e2d...\")<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(1)<br>\u200b<br>\u200b<br>d = threading.Thread(target=daemon_worker, daemon=True)<br>d.start()<br>\u200b<br>time.sleep(3)<br>print(\"\u4e3b\u7ebf\u7a0b\u7ed3\u675f\uff0c\u5b88\u62a4\u7ebf\u7a0b\u88ab\u5f3a\u5236\u7ec8\u6b62\")<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\u6ce8\u610f\uff1a\u5b88\u62a4\u7ebf\u7a0b\u4e2d\u4e0d\u5e94\u64cd\u4f5c\u8d44\u6e90\uff08\u5982\u5199\u6587\u4ef6\uff09\uff0c\u56e0\u4e3a\u53ef\u80fd\u5728\u64cd\u4f5c\u8fc7\u7a0b\u4e2d\u88ab\u5f3a\u5236\u7ec8\u6b62\u3002<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">\u7ebf\u7a0b\u5b89\u5168\u4e0e\u7ade\u6001\u6761\u4ef6<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">\u591a\u4e2a\u7ebf\u7a0b\u540c\u65f6\u8bbf\u95ee\u5171\u4eab\u53d8\u91cf\u65f6\uff0c\u4f1a\u51fa\u73b0<strong>\u7ade\u6001\u6761\u4ef6 (Race Condition)<\/strong>\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>class BankAccount:<br> &nbsp; &nbsp;def __init__(self, balance):<br> &nbsp; &nbsp; &nbsp; &nbsp;self.balance = balance<br>\u200b<br>\u200b<br>def withdraw(account, amount, person_name):<br> &nbsp; &nbsp;\"\"\"\u53d6\u6b3e\u51fd\u6570 - \u6709\u7ade\u6001\u6761\u4ef6\u6f0f\u6d1e\"\"\"<br> &nbsp; &nbsp;print(f\"{person_name}: \u67e5\u8be2\u4f59\u989d\uff0c\u5f53\u524d\u6709 {account.balance} \u5143\")<br>\u200b<br> &nbsp; &nbsp;# \u5173\u952e\u6f0f\u6d1e\uff1a\u68c0\u67e5\u4f59\u989d\u548c\u6263\u6b3e\u4e0d\u662f\u539f\u5b50\u64cd\u4f5c<br> &nbsp; &nbsp;if account.balance &gt;= amount:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{person_name}: \u4f59\u989d\u5145\u8db3\uff0c\u5f00\u59cb\u53d6\u6b3e...\")<br>\u200b<br> &nbsp; &nbsp; &nbsp; &nbsp;# \u8fd9\u4e2a\u5ef6\u8fdf\u8ba9\u53e6\u4e00\u4e2a\u7ebf\u7a0b\u6709\u673a\u4f1a\u63d2\u8fdb\u6765<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(0.1) &nbsp;# \u6a21\u62df\u8f93\u5165\u5bc6\u7801\u3001\u51fa\u949e\u7b49\u8fc7\u7a0b<br>\u200b<br> &nbsp; &nbsp; &nbsp; &nbsp;# \u6263\u6b3e<br> &nbsp; &nbsp; &nbsp; &nbsp;account.balance -= amount<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{person_name}: \u2713 \u53d6\u6b3e{amount}\u5143\u6210\u529f\uff01\u5269\u4f59 {account.balance} \u5143\")<br> &nbsp; &nbsp; &nbsp; &nbsp;return True<br> &nbsp; &nbsp;else:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{person_name}: \u2717 \u4f59\u989d\u4e0d\u8db3\uff0c\u53d6\u6b3e\u5931\u8d25\")<br> &nbsp; &nbsp; &nbsp; &nbsp;return False<br>\u200b<br>\u200b<br># \u521b\u5efa\u4e00\u4e2a\u8d26\u6237\uff0c\u4f59\u989d1000\u5143<br>account = BankAccount(1000)<br>\u200b<br># \u4e24\u4e2a\u4eba\u540c\u65f6\u53d6\u6b3e800\u5143<br>person1 = threading.Thread(target=withdraw, args=(account, 800, \"\u5f20\u4e09\"))<br>person2 = threading.Thread(target=withdraw, args=(account, 800, \"\u674e\u56db\"))<br>\u200b<br># \u540c\u65f6\u542f\u52a8<br>print(\"=== \u4e24\u4e2a\u4eba\u540c\u65f6\u5f00\u59cb\u53d6\u6b3e ===\")<br>person1.start()<br>person2.start()<br>\u200b<br># \u7b49\u5f85\u4e24\u4eba\u5b8c\u6210<br>person1.join()<br>person2.join()<br>\u200b<br>print(\"\\n=== \u6700\u7ec8\u7ed3\u679c ===\")<br>print(f\"\u8d26\u6237\u4f59\u989d: {account.balance} \u5143\")<br>print(f\"\u5982\u679c\u6b63\u5e38\uff0c\u5e94\u8be5\u53ea\u5269: {1000 - 800} = 200 \u5143\")<br>print(f\"\u4e24\u4eba\u5171\u53d6\u51fa\u4e86: {1600 - account.balance} \u5143\")<br>\u200b<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><code>account.balance -= amount<\/code> \u5e76\u975e\u539f\u5b50\u64cd\u4f5c\uff0c\u5b83\u5bf9\u5e94\u4e09\u6761 CPU \u6307\u4ee4\uff1a<code>LOAD balance<\/code> \u2192 <code>SUB amount<\/code> \u2192 <code>STORE balance<\/code>\u3002\u7ebf\u7a0b\u5207\u6362\u53ef\u80fd\u53d1\u751f\u5728\u4efb\u610f\u4e24\u6761\u6307\u4ee4\u4e4b\u95f4\u3002\u66f4\u5173\u952e\u7684\u662f\uff0c<strong>\u68c0\u67e5\u4f59\u989d\u548c\u6263\u6b3e\u8fd9\u4e24\u4e2a\u6b65\u9aa4\u4e4b\u95f4<\/strong>\u4e5f\u5b58\u5728\u65f6\u95f4\u7a97\u53e3\u3002<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">Lock \u2014\u2014 \u4e92\u65a5\u9501<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Lock<\/code> \u786e\u4fdd\u540c\u4e00\u65f6\u523b\u53ea\u6709\u4e00\u4e2a\u7ebf\u7a0b\u53ef\u4ee5\u8bbf\u95ee\u4e34\u754c\u533a\uff0c\u7528\u9501\u4fee\u590d\u4e0a\u9762\u7684\u94f6\u884c\u8d26\u6237\u95ee\u9898\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>class BankAccount:<br> &nbsp; &nbsp;def __init__(self, balance):<br> &nbsp; &nbsp; &nbsp; &nbsp;self.balance = balance<br> &nbsp; &nbsp; &nbsp; &nbsp;self._lock = threading.Lock()<br>\u200b<br>\u200b<br>def withdraw(account: BankAccount, amount: int, person_name: str):<br> &nbsp; &nbsp;\"\"\"\u53d6\u6b3e\u51fd\u6570 - \u4f7f\u7528\u9501\u4fdd\u8bc1\u7ebf\u7a0b\u5b89\u5168\"\"\"<br> &nbsp; &nbsp;with account._lock: &nbsp;# \u83b7\u53d6\u9501\uff0c\u540c\u4e00\u65f6\u523b\u53ea\u6709\u4e00\u4e2a\u7ebf\u7a0b\u80fd\u8fdb\u5165<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{person_name}: \u67e5\u8be2\u4f59\u989d\uff0c\u5f53\u524d\u6709 {account.balance} \u5143\")<br>\u200b<br> &nbsp; &nbsp; &nbsp; &nbsp;if account.balance &gt;= amount:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{person_name}: \u4f59\u989d\u5145\u8db3\uff0c\u5f00\u59cb\u53d6\u6b3e...\")<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(0.1)<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;account.balance -= amount<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{person_name}: \u2713 \u53d6\u6b3e{amount}\u5143\u6210\u529f\uff01\u5269\u4f59 {account.balance} \u5143\")<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return True<br> &nbsp; &nbsp; &nbsp; &nbsp;else:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{person_name}: \u2717 \u4f59\u989d\u4e0d\u8db3\uff0c\u53d6\u6b3e\u5931\u8d25\")<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return False<br>\u200b<br>\u200b<br>account = BankAccount(1000)<br>\u200b<br>person1 = threading.Thread(target=withdraw, args=(account, 800, \"\u5f20\u4e09\"))<br>person2 = threading.Thread(target=withdraw, args=(account, 800, \"\u674e\u56db\"))<br>\u200b<br>print(\"=== \u4e24\u4e2a\u4eba\u540c\u65f6\u5f00\u59cb\u53d6\u6b3e ===\")<br>person1.start()<br>person2.start()<br>person1.join()<br>person2.join()<br>\u200b<br>print(\"\\n=== \u6700\u7ec8\u7ed3\u679c ===\")<br>print(f\"\u8d26\u6237\u4f59\u989d: {account.balance} \u5143\")<br>print(f\"\u5982\u679c\u6b63\u5e38\uff0c\u5e94\u8be5\u53ea\u5269: {1000 - 800} = 200 \u5143\")<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u9501\u7684\u5e38\u89c1\u95ee\u9898\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>\u200b<br>\u200b<br>lock = threading.Lock()<br>\u200b<br># \u540c\u4e00\u4e2a\u7ebf\u7a0b\u91cd\u590d acquire \u4f1a\u6b7b\u9501<br>lock.acquire()<br>lock.acquire() &nbsp;# \u6b7b\u9501\uff01\u6211\u9501\u6211\u81ea\u5df1 \u2014\u2014 \u56e0\u4e3a\u7ebf\u7a0b\u8fd8\u6ca1\u91ca\u653e\u5c31\u518d\u6b21\u7533\u8bf7<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">RLock \u2014\u2014 \u53ef\u91cd\u5165\u9501<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>RLock<\/code> \u5141\u8bb8\u540c\u4e00\u4e2a\u7ebf\u7a0b\u591a\u6b21 acquire\uff0c\u5185\u90e8\u7ef4\u62a4\u4e00\u4e2a\u8ba1\u6570\u5668\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>\u200b<br>lock = threading.RLock()<br>\u200b<br>\u200b<br>def recurse(n: int):<br> &nbsp; &nbsp;with lock:<br> &nbsp; &nbsp; &nbsp; &nbsp;if n &gt; 0:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(f\"Recursing with n={n}\")<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;recurse(n - 1) &nbsp;# \u540c\u4e00\u4e2a\u7ebf\u7a0b\u518d\u6b21 acquire \u2705<br>\u200b<br>\u200b<br>recurse(5) &nbsp;# \u6b63\u5e38\u8fd0\u884c<br>\u200b<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Semaphore \u2014\u2014 \u9650\u5236\u5e76\u53d1\u6570<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>semaphore = threading.Semaphore(3)<br>\u200b<br>\u200b<br>def limited_worker(n: int):<br> &nbsp; &nbsp;with semaphore:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"\u7ebf\u7a0b {n} \u8fdb\u5165\\n\", end=\"\")<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(1)<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"\u7ebf\u7a0b {n} \u79bb\u5f00\\n\", end=\"\")<br>\u200b<br>\u200b<br>threads = &#91;threading.Thread(target=limited_worker, args=(i,)) for i in range(10)]<br>\u200b<br>for t in threads:<br> &nbsp; &nbsp;t.start()<br>for t in threads:<br> &nbsp; &nbsp;t.join()<br>\u200b<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Event \u2014\u2014 \u7ebf\u7a0b\u95f4\u901a\u77e5<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>event = threading.Event()<br>\u200b<br>\u200b<br>def waiter():<br> &nbsp; &nbsp;print(\"waiter: \u5f00\u59cb\u7b49\u5f85\")<br> &nbsp; &nbsp;event.wait() &nbsp;# \u7b49\u5f85\u4e8b\u4ef6\u88ab\u8bbe\u7f6e<br> &nbsp; &nbsp;print(\"waiter: \u88ab\u5524\u9192\")<br>\u200b<br>\u200b<br>def setter():<br> &nbsp; &nbsp;print(\"setter: 1\u79d2\u540e\u8bbe\u7f6e\u4e8b\u4ef6\")<br> &nbsp; &nbsp;time.sleep(1)<br> &nbsp; &nbsp;event.set()<br> &nbsp; &nbsp;print(\"setter: \u4e8b\u4ef6\u5df2\u8bbe\u7f6e\")<br>\u200b<br>\u200b<br>t1 = threading.Thread(target=waiter)<br>t2 = threading.Thread(target=setter)<br>t1.start()<br>t2.start()<br>t1.join()<br>t2.join()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">waiter: \u5f00\u59cb\u7b49\u5f85<br>setter: 1\u79d2\u540e\u8bbe\u7f6e\u4e8b\u4ef6<br>setter: \u4e8b\u4ef6\u5df2\u8bbe\u7f6e<br>waiter: \u88ab\u5524\u9192<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Queue \u2014\u2014 \u7ebf\u7a0b\u5b89\u5168\u7684\u751f\u4ea7\u8005\u6d88\u8d39\u8005<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import queue<br>import random<br>import threading<br>import time<br>\u200b<br>\u200b<br>def producer(q: queue.Queue):<br> &nbsp; &nbsp;for i in range(10):<br> &nbsp; &nbsp; &nbsp; &nbsp;item = f\"item_{i}\"<br> &nbsp; &nbsp; &nbsp; &nbsp;q.put(item)<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"\u751f\u4ea7: {item}\\n\", end=\"\")<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(random.random())<br> &nbsp; &nbsp;q.put(None)<br>\u200b<br>\u200b<br>def consumer(name: str, q: queue.Queue):<br> &nbsp; &nbsp;while True:<br> &nbsp; &nbsp; &nbsp; &nbsp;item = q.get()<br> &nbsp; &nbsp; &nbsp; &nbsp;if item is None:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;q.task_done()<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{name} \u6d88\u8d39: {item}\\n\", end=\"\")<br> &nbsp; &nbsp; &nbsp; &nbsp;q.task_done()<br>\u200b<br>\u200b<br>q = queue.Queue(maxsize=5)<br>threads = &#91;<br> &nbsp; &nbsp;threading.Thread(target=producer, args=(q,)),<br> &nbsp; &nbsp;threading.Thread(target=consumer, args=(\"C1\", q)),<br> &nbsp; &nbsp;threading.Thread(target=consumer, args=(\"C2\", q)),<br>]<br>\u200b<br>for t in threads:<br> &nbsp; &nbsp;t.start()<br>for t in threads:<br> &nbsp; &nbsp;t.join()<br>\u200b<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><code>queue.Queue<\/code> \u5185\u90e8\u5df2\u7ecf\u5b9e\u73b0\u4e86\u7ebf\u7a0b\u540c\u6b65\uff0c\u65e0\u9700\u989d\u5916\u52a0\u9501\u3002<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">ThreadPoolExecutor \u2014\u2014 \u7ebf\u7a0b\u6c60<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">\u9891\u7e41\u521b\u5efa\u7ebf\u7a0b\u5f00\u9500\u5927\uff0c\u4f7f\u7528\u7ebf\u7a0b\u6c60\u590d\u7528\u7ebf\u7a0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from concurrent.futures import ThreadPoolExecutor<br>import time<br>\u200b<br>\u200b<br>def fetch_url(url: str) -&gt; str:<br> &nbsp; &nbsp;time.sleep(1) &nbsp;# \u6a21\u62df\u7f51\u7edc\u8bf7\u6c42<br> &nbsp; &nbsp;return f\"{url} \u5b8c\u6210\"<br>\u200b<br>\u200b<br>with ThreadPoolExecutor(max_workers=3) as executor:<br> &nbsp; &nbsp;urls = &#91;\"url1\", \"url2\", \"url3\", \"url4\", \"url5\"]<br>\u200b<br> &nbsp; &nbsp;# map \u8fd4\u56de\u7ed3\u679c\u7684\u987a\u5e8f\u4e0e\u4f20\u5165\u987a\u5e8f\u4e00\u81f4<br> &nbsp; &nbsp;results = executor.map(fetch_url, urls)<br> &nbsp; &nbsp;for r in results:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(r)<br>\u200b<br> &nbsp; &nbsp;# \u4e5f\u53ef\u4ee5 submit \u9010\u6761\u63d0\u4ea4<br> &nbsp; &nbsp;futures = &#91;executor.submit(fetch_url, url) for url in urls]<br> &nbsp; &nbsp;for f in futures:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f.result())<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">ThreadPoolExecutor \u4e0e asyncio \u914d\u5408<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio<br>import time<br>from concurrent.futures import ThreadPoolExecutor<br>\u200b<br>\u200b<br>def blocking_io() -&gt; str:<br> &nbsp; &nbsp;time.sleep(0.5) &nbsp;# \u540c\u6b65\u963b\u585e<br> &nbsp; &nbsp;return \"\u6587\u4ef6\u8bfb\u53d6\u5b8c\u6210\"<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;# to_thread \u5c06\u540c\u6b65\u963b\u585e\u51fd\u6570\u653e\u5230\u7ebf\u7a0b\u6c60\u4e2d\u6267\u884c<br> &nbsp; &nbsp;result = await asyncio.to_thread(blocking_io)<br> &nbsp; &nbsp;print(result)<br>\u200b<br> &nbsp; &nbsp;# \u4e5f\u53ef\u4ee5\u624b\u52a8\u6307\u5b9a\u6267\u884c\u5668<br> &nbsp; &nbsp;loop = asyncio.get_running_loop()<br> &nbsp; &nbsp;with ThreadPoolExecutor() as pool:<br> &nbsp; &nbsp; &nbsp; &nbsp;result = await loop.run_in_executor(pool, blocking_io)<br> &nbsp; &nbsp; &nbsp; &nbsp;print(result)<br>\u200b<br>\u200b<br>asyncio.run(main())<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u7ebf\u7a0b\u5c40\u90e8\u6570\u636e (Thread Local)<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">\u6bcf\u4e2a\u7ebf\u7a0b\u62e5\u6709\u72ec\u7acb\u7684\u526f\u672c\uff0c\u4e92\u4e0d\u5e72\u6270\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>local_data = threading.local()<br>\u200b<br>\u200b<br>def worker(name: str):<br> &nbsp; &nbsp;local_data.name = name &nbsp;# \u6bcf\u4e2a\u7ebf\u7a0b\u72ec\u7acb\u5b58\u50a8<br> &nbsp; &nbsp;local_data.count = 0<br> &nbsp; &nbsp;for _ in range(3):<br> &nbsp; &nbsp; &nbsp; &nbsp;local_data.count += 1<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"{local_data.name}: {local_data.count}\")<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(0.1)<br>\u200b<br>\u200b<br>threads = &#91;<br> &nbsp; &nbsp;threading.Thread(target=worker, args=(\"A\",)),<br> &nbsp; &nbsp;threading.Thread(target=worker, args=(\"B\",)),<br>]<br>\u200b<br>for t in threads:<br> &nbsp; &nbsp;t.start()<br>for t in threads:<br> &nbsp; &nbsp;t.join()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u591a\u7ebf\u7a0b\u5e38\u89c1\u95ee\u9898<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">GIL \u2014\u2014 \u5168\u5c40\u89e3\u91ca\u5668\u9501<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">CPython \u4e2d\u6709\u4e00\u4e2a <strong>GIL (Global Interpreter Lock)<\/strong>\uff0c\u5b83\u4fdd\u8bc1\u540c\u4e00\u65f6\u523b\u53ea\u6709\u4e00\u4e2a\u7ebf\u7a0b\u5728\u6267\u884c Python \u5b57\u8282\u7801\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>def cpu_intensive():<br> &nbsp; &nbsp;total = 0<br> &nbsp; &nbsp;for i in range(50_000_000):<br> &nbsp; &nbsp; &nbsp; &nbsp;total += i * i<br> &nbsp; &nbsp;return total<br>\u200b<br>\u200b<br># \u591a\u7ebf\u7a0b vs \u5355\u7ebf\u7a0b \u2014\u2014 \u591a\u7ebf\u7a0b\u4e0d\u4f1a\u66f4\u5feb\uff01<br>t1 = threading.Thread(target=cpu_intensive)<br>t2 = threading.Thread(target=cpu_intensive)<br>\u200b<br>start = time.time()<br>t1.start()<br>t2.start()<br>t1.join()<br>t2.join()<br>print(f\"\u591a\u7ebf\u7a0b: {time.time() - start:.2f}s\")<br>\u200b<br>start = time.time()<br>cpu_intensive()<br>cpu_intensive()<br>print(f\"\u5355\u7ebf\u7a0b: {time.time() - start:.2f}s\")<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">GIL \u7684\u5b58\u5728\u610f\u5473\u7740\uff1a<strong>Python \u591a\u7ebf\u7a0b\u65e0\u6cd5\u5229\u7528\u591a\u6838 CPU \u52a0\u901f CPU \u5bc6\u96c6\u578b\u4efb\u52a1<\/strong>\u3002<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u90a3\u591a\u7ebf\u7a0b\u7684\u610f\u4e49\u5728\u54ea\uff1f\u5bf9\u4e8e <strong>I\/O \u5bc6\u96c6\u578b<\/strong> \u4efb\u52a1\uff0c\u7ebf\u7a0b\u5728\u7b49\u5f85 I\/O \u65f6\u4f1a\u91ca\u653e GIL\uff0c\u5176\u4ed6\u7ebf\u7a0b\u53ef\u4ee5\u7ee7\u7eed\u6267\u884c\uff0c\u6240\u4ee5\u4ecd\u7136\u6709\u52a0\u901f\u6548\u679c\u3002<\/p>\n<\/blockquote>\n\n\n\n<h3 class=\"wp-block-heading\">CPU \u5bc6\u96c6\u578b \u2014\u2014 \u5e94\u8be5\u7528\u591a\u8fdb\u7a0b<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>from multiprocessing import Process<br>\u200b<br>\u200b<br>def cpu_intensive():<br> &nbsp; &nbsp;total = 0<br> &nbsp; &nbsp;for i in range(50_000_000):<br> &nbsp; &nbsp; &nbsp; &nbsp;total += i * i<br> &nbsp; &nbsp;return total<br>\u200b<br>\u200b<br>p1 = Process(target=cpu_intensive)<br>p2 = Process(target=cpu_intensive)<br>p1.start()<br>p2.start()<br>p1.join()<br>p2.join()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">\u6b7b\u9501<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>lock_a = threading.Lock()<br>lock_b = threading.Lock()<br>\u200b<br>\u200b<br>def task_1():<br> &nbsp; &nbsp;with lock_a:<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(0.1)<br> &nbsp; &nbsp; &nbsp; &nbsp;with lock_b: &nbsp;# \u7b49\u5f85 lock_b<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(\"task_1 \u5b8c\u6210\")<br>\u200b<br>\u200b<br>def task_2():<br> &nbsp; &nbsp;with lock_b:<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(0.1)<br> &nbsp; &nbsp; &nbsp; &nbsp;with lock_a: &nbsp;# \u7b49\u5f85 lock_a<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(\"task_2 \u5b8c\u6210\")<br>\u200b<br>\u200b<br>t1 = threading.Thread(target=task_1)<br>t2 = threading.Thread(target=task_2)<br>t1.start()<br>t2.start()<br>t1.join()<br>t2.join()<br># \u6b7b\u9501\uff01\u4e24\u4e2a\u7ebf\u7a0b\u4e92\u76f8\u7b49\u5f85\u5bf9\u65b9\u91ca\u653e\u9501<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u89e3\u51b3\u6b7b\u9501\u7684\u539f\u5219\uff1a<strong>\u56fa\u5b9a\u9501\u7684\u83b7\u53d6\u987a\u5e8f<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading<br>import time<br>\u200b<br>\u200b<br>lock_a = threading.Lock()<br>lock_b = threading.Lock()<br>\u200b<br>\u200b<br>def task_1():<br> &nbsp; &nbsp;with lock_a:<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(0.1)<br> &nbsp; &nbsp; &nbsp; &nbsp;with lock_b:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(\"task_1 \u5b8c\u6210\")<br>\u200b<br>\u200b<br>def task_2():<br> &nbsp; &nbsp;with lock_a: &nbsp;# \u4e0e task_1 \u83b7\u53d6\u9501\u7684\u987a\u5e8f\u4e00\u81f4<br> &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(0.1)<br> &nbsp; &nbsp; &nbsp; &nbsp;with lock_b:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(\"task_2 \u5b8c\u6210\")<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u4f55\u65f6\u7528\u7ebf\u7a0b\uff0c\u4f55\u65f6\u7528\u534f\u7a0b\uff1f<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th class=\"has-text-align-left\" data-align=\"left\">\u573a\u666f<\/th><th class=\"has-text-align-left\" data-align=\"left\">\u63a8\u8350\u65b9\u6848<\/th><\/tr><\/thead><tbody><tr><td class=\"has-text-align-left\" data-align=\"left\">CPU \u5bc6\u96c6\u578b<\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>multiprocessing<\/code> \/ <code>ProcessPoolExecutor<\/code><\/td><\/tr><tr><td class=\"has-text-align-left\" data-align=\"left\">\u540c\u6b65 I\/O \u5bc6\u96c6\u578b\uff08\u6587\u4ef6\u8bfb\u5199\u3001\u6570\u636e\u5e93\u9a71\u52a8\u963b\u585e\uff09<\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>threading<\/code> \/ <code>ThreadPoolExecutor<\/code><\/td><\/tr><tr><td class=\"has-text-align-left\" data-align=\"left\">\u5f02\u6b65 I\/O \u5bc6\u96c6\u578b\uff08\u7f51\u7edc\u722c\u866b\u3001Web \u670d\u52a1\uff09<\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>asyncio<\/code> \/ \u534f\u7a0b<\/td><\/tr><tr><td class=\"has-text-align-left\" data-align=\"left\">\u8c03\u7528\u7b2c\u4e09\u65b9\u540c\u6b65\u5e93<\/td><td class=\"has-text-align-left\" data-align=\"left\">\u7528 <code>asyncio.to_thread<\/code> \u6216 <code>run_in_executor<\/code> \u5305\u88c5<\/td><\/tr><\/tbody><\/table><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>threading \u6a21\u5757 threading \u662f ..<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[52,14],"tags":[],"class_list":["post-744","post","type-post","status-publish","format-standard","hentry","category-python","category-back"],"featured_image_urls":{"full":"","thumbnail":"","medium":"","medium_large":"","large":"","1536x1536":"","2048x2048":""},"author_info":{"info":["\u9648 \u67d0\u4eba"]},"category_info":"<a href=\"https:\/\/mitongxue.cn\/index.php\/category\/back\/python\/\" rel=\"category tag\">Python<\/a> <a href=\"https:\/\/mitongxue.cn\/index.php\/category\/back\/\" rel=\"category tag\">\u540e\u7aef<\/a>","tag_info":"\u540e\u7aef","comment_count":"0","_links":{"self":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/744","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/comments?post=744"}],"version-history":[{"count":1,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/744\/revisions"}],"predecessor-version":[{"id":745,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/744\/revisions\/745"}],"wp:attachment":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/media?parent=744"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/categories?post=744"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/tags?post=744"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}