中断主线程并要求它做一些事情

interrupt main thread and ask it to do something

本文关键字:线程 中断      更新时间:2023-10-16

我想知道是否有可能中断主线程并要求它执行一些回调。主线程应该在完成回调后继续它正在做的事情。

例如,我们有两个线程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");
  }
}