Pankaj Bansal Pankaj Bansal - 11 months ago 46
C Question

interrupt main thread and ask it to do something

I want to know if its possible to interrupt main thread and ask it to execute some callback. The main thread should continue with what it was doing after completing the callback.

For instance, we have 2 threads t1 and m1 (main thread). t1 will interrupt m1 (main thread) and ask it to call a function with some parameters. The m1 (main thread) will stop doing what it was doing before and will start executing the function. The after finishing the function, it will get back to what it was doing earlier.

I want to replicate what hardware interrupt does. I have one thread that reads data from a file. Then it should ask main thread to call a function. Main thread will be doing something. It should stop doing it and start executing the function. After completing it, main thread should continue with what it was doing

Answer Source

A clean way I think would be to have a queue of operations that t1 adds to, that t2 checks at points in its processing loop where it is safe to start doing something else.

On POSIX systems, you can use signals. For example, the following starts a second thread and, while the main thread is doing other work, this second thread sends it a SIGUSR1 signal. The main thread handles it and resumes operation.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>

void* other_thread(void* main_thread) {
  printf("other_thread: %x\n", pthread_self());
  printf("sending SIGUSR1 to main thread...\n");
  pthread_kill((pthread_t) main_thread, SIGUSR1);
  return NULL; 

void my_handler(int signal) {
  printf("my_handler: %x\n", pthread_self());
  printf("back to main\n");

int main(int argc, char**argv) {

  signal(SIGUSR1, my_handler);

  pthread_t thread1;
  pthread_create(&thread1, NULL, other_thread, pthread_self());

  printf("main: %x\n", pthread_self());
  int x = 0;
  while (1) {
    // sleep(1), or do some work, or:
    if (x % 10000000 == 0) printf("boo\n");