Python中文
首页
教程
问答
标签
搜索
登录
注册
Python中的可中断线程连接
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p><strong>是否有方法等待线程终止,但仍截获信号?</strong></p> <p>考虑以下<strong>C</strong>程序:</p> <pre><code>#include <signal.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> void* server_thread(void* dummy) { sleep(10); printf("Served\n"); return NULL; } void* kill_thread(void* dummy) { sleep(1); // Let the main thread join printf("Killing\n"); kill(getpid(), SIGUSR1); return NULL; } void handler(int signum) { printf("Handling %d\n", signum); exit(42); } int main() { pthread_t servth; pthread_t killth; signal(SIGUSR1, handler); pthread_create(&servth, NULL, server_thread, NULL); pthread_create(&killth, NULL, kill_thread, NULL); pthread_join(servth, NULL); printf("Main thread finished\n"); return 0; } </code></pre> <p>一秒钟后结束打印:</p> <pre><code>Killing Handling 10 </code></pre> <p>相比之下,我尝试用Python编写它:</p> <pre><code>#!/usr/bin/env python import signal, time, threading, os, sys def handler(signum, frame): print("Handling " + str(signum) + ", frame:" + str(frame)) exit(42) signal.signal(signal.SIGUSR1, handler) def server_thread(): time.sleep(10) print("Served") servth = threading.Thread(target=server_thread) servth.start() def kill_thread(): time.sleep(1) # Let the main thread join print("Killing") os.kill(os.getpid(), signal.SIGUSR1) killth = threading.Thread(target=kill_thread) killth.start() servth.join() print("Main thread finished") </code></pre> <p>它打印:</p> <pre><code>Killing Served Handling 10, frame:<frame object at 0x12649c0> </code></pre> <p><strong>我该如何让它表现得像C版本?</strong></p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>在调用<code>join</code>之前对<code>isAlive</code>进行轮询。当然,这种轮询可以被中断,一旦线程没有<code>isAlive</code>,就可以立即<code>join</code>。</p> <p>另一种方法是使用超时在<code>join</code>上轮询,使用<code>isAlive</code>检查是否发生超时。这会比以前的方法花费更少的CPU。</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何在python中从数据帧列中删除分类值?
9 回答
如何在python中从数据帧列表中删除引号
1 回答
如何在python中从数据帧创建列表
6 回答
如何在Python中从数据帧创建嵌套的JSON
1 回答
如何在Python中从数据帧显示wordcloud
10 回答
如何在Python中从数据帧的时间戳中删除字符
1 回答
如何在Python中从数据帧绘制简单绘图?
1 回答
如何在python中从数据帧行提取具有特定长度的范围?
6 回答
如何在python中从数据帧设置dict中的值
8 回答
如何在Python中从数据库中获得一个结果
5 回答
如何在python中从数据框中绘制分类条形图
6 回答
如何在Python中从数据框中选择特定细节?
3 回答
如何在python中从数据集中删除unicode
1 回答
如何在python中从数据集中删除某些数值?
6 回答
如何在python中从数据集中选择行
8 回答
如何在Python中从数组中删除元素
2 回答
如何在python中从数组中删除单个倒逗号?
8 回答
如何在python中从数组中删除对象?
2 回答
如何在python中从数组中删除引号
2 回答
如何在python中从数组中删除所有最小值
3 回答