相关疑难解决方法(0)

有没有办法杀死一个线程?

是否可以在不设置/检查任何标志/信号量/等的情况下终止正在运行的线程?

python multithreading kill terminate

710
推荐指数
16
解决办法
71万
查看次数

无法使用Ctrl-C终止Python脚本

我正在使用以下脚本测试Python线程:

import threading

class FirstThread (threading.Thread):
    def run (self):
        while True:
            print 'first'

class SecondThread (threading.Thread):
    def run (self):
        while True:
            print 'second'

FirstThread().start()
SecondThread().start()
Run Code Online (Sandbox Code Playgroud)

这是在Kubuntu 11.10上的Python 2.7中运行的.Ctrl+ C不会杀了它.我也尝试为系统信号添加处理程序,但这没有帮助:

import signal 
import sys
def signal_handler(signal, frame):
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
Run Code Online (Sandbox Code Playgroud)

为了杀死进程,我在用Ctrl+ 发送程序到后台后通过PID将其杀死Z,这是不被忽略的.为什么Ctrl+ C如此坚持被忽视?我该如何解决这个问题?

python linux

109
推荐指数
3
解决办法
8万
查看次数

Python中的可中断线程连接

有没有办法等待终止线程,但仍然拦截信号?

考虑以下C程序:

#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;
}
Run Code Online (Sandbox Code Playgroud)

它在一秒后结束并打印:

Killing
Handling 10 …
Run Code Online (Sandbox Code Playgroud)

python multithreading

23
推荐指数
2
解决办法
1万
查看次数

如何在线程化时中断 Python I/O 操作?

例如,

with open("foo") as f:
  f.read()
Run Code Online (Sandbox Code Playgroud)

(但它可能是文件写入、DNS 查找、任意数量的其他 I/O 操作。)

如果我在读取 (SIGINT) 时中断该程序,则 I/O 操作将停止并被KeyboardInterrupt抛出,并且终结器会运行。

但是,如果这发生在主线程以外的线程上,则 I/O 操作不会中断。

那么...如何中断另一个线程上的 I/O 操作(类似于它在主线程上的中断方式)?

python io multithreading signals sigint

8
推荐指数
1
解决办法
279
查看次数

使用threading.Timer时,Ctrl-C不起作用

我正在Windows上编写一个多线程Python应用程序.

我曾经使用过终止应用程序ctrl-c,但是一旦我添加了threading.Timer实例ctrl-c停止工作(或者有时需要很长时间).

怎么会这样?
具有Timer线程和ctrl-c?之间的关系是什么?

更新:
我在Python的线程文档中发现了以下内容:

线程与中断奇怪地交互:KeyboardInterrupt异常将由任意线程接收.(当信号模块可用时,中断始终转到主线程.)

python multithreading timer

6
推荐指数
1
解决办法
3598
查看次数

标签 统计

python ×5

multithreading ×4

io ×1

kill ×1

linux ×1

sigint ×1

signals ×1

terminate ×1

timer ×1