中断主线程并要求它做一些事情
interrupt main thread and ask it to do something
我想知道是否有可能中断主线程并要求它执行一些回调。主线程应该在完成回调后继续它正在做的事情。
例如,我们有两个线程t1和m1(主线程)。T1将中断m1(主线程),并要求它调用带有一些参数的函数。m1(主线程)将停止做它之前做的事情,并将开始执行函数。在完成函数后,它将返回到它之前所做的事情。
我想复制硬件中断的功能。我有一个线程从文件中读取数据。然后它应该要求主线程调用一个函数。主线程会做一些事情。它应该停止这样做,并开始执行函数。完成后,主线程应该继续它正在做的事情
我认为一种干净的方式是有一个t1添加的操作队列,t2检查其处理循环中的点,在哪里可以安全开始做其他事情。
在POSIX系统上,可以使用信号。例如,下面的代码启动了第二个线程,当主线程正在做其他工作时,第二个线程向它发送一个SIGUSR1
信号。主线程处理它并继续操作。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
void* other_thread(void* main_thread) {
printf("other_thread: %xn", pthread_self());
usleep(250*1000);
printf("sending SIGUSR1 to main thread...n");
pthread_kill((pthread_t) main_thread, SIGUSR1);
return NULL;
}
void my_handler(int signal) {
printf("my_handler: %xn", pthread_self());
sleep(2);
printf("back to mainn");
}
int main(int argc, char**argv) {
signal(SIGUSR1, my_handler);
pthread_t thread1;
pthread_create(&thread1, NULL, other_thread, pthread_self());
printf("main: %xn", pthread_self());
int x = 0;
while (1) {
// sleep(1), or do some work, or:
x++;
if (x % 10000000 == 0) printf("boon");
}
}
相关文章:
- 使用 shared_ptr 在中断时结束多线程循环
- 如何使用 SIGINT 在第二个线程中断 getchar
- 可中断线程类 C++11 - 遇到错误?
- 指向成员对象的指针 - 中断线程
- 处理中断时,如何回到主gui线程
- 在 Visual Studio 中的调试中断时设置默认线程,C++
- 返回可中断线程的函数
- 多线程应用程序中的零MQ处理中断
- C++等待用户输入的中断线程
- 如何中断Asynch线程
- 捕获升压线程中断和退出线程的正确方法
- 异步过程调用被另一个线程中断
- 在Windows上使用WaitForSingleObject,但支持boost线程中断
- 提升线程 - 安全/有保证的处理线程中断的方式
- 从另一个线程中断c++中的lua脚本
- 从另一个线程中断event_base_dispatch
- c++多线程中断
- 线程中断与插槽和信号
- 从另一个线程中断boost::asio::async_receive_from
- 阻塞线程中断