相关疑难解决方法(0)

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程序无法捕获CTRL + C.

我正在编写一个python脚本,需要运行一个侦听网络套接字的线程.

我使用以下代码使用Ctrl+ 杀死它时遇到了麻烦c:

#!/usr/bin/python

import signal, sys, threading

THREADS = []

def handler(signal, frame):
    global THREADS
    print "Ctrl-C.... Exiting"
    for t in THREADS:
        t.alive = False
    sys.exit(0)

class thread(threading.Thread):
    def __init__(self):
        self.alive = True
        threading.Thread.__init__(self)


    def run(self):
        while self.alive:
            # do something
            pass

def main():
    global THREADS
    t = thread()
    t.start()
    THREADS.append(t)

if __name__ == '__main__':
    signal.signal(signal.SIGINT, handler)
    main()
Run Code Online (Sandbox Code Playgroud)

欣赏有关如何捕获Ctrl+ c并终止脚本的任何建议.

python multithreading

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

标签 统计

multithreading ×2

python ×2