1

I am very newcomer to multi thread programming, so this question might seem a little silly , Follow is my code, I am trying to have 2 threads :

struct sigaction    S1,S2;
struct itimerval    T1,T2;

void Function1(){
    cout<<"Function1 "<<endl;
}   
void Function2(){
    cout<<"Function2 "<<endl;
} 

void Thread_Function(){
    int t=70000;
    memset (&s2, 0, sizeof (s2));
    s2.sa_handler = &Function2;

    sigaction (SIGALRM, &s2, NULL);

    sigemptyset(&s2.sa_mask);
    s2.sa_flags = 0;

    T2.it_value.tv_sec = 0;
    T2.it_value.tv_usec =t;
    T2.it_interval.tv_sec =0;
    T2.it_interval.tv_usec =t;
    setitimer (ITIMER_REAL, &T2, NULL);
} 

int main(){

    int t=50000;
    memset (&s1, 0, sizeof (s1));
    s1.sa_handler = &Function1;

    sigaction (SIGALRM, &s1, NULL);

    sigemptyset(&s1.sa_mask);
    s1.sa_flags = 0;

    T1.it_value.tv_sec = 0;
    T1.it_value.tv_usec =t;
    T1.it_interval.tv_sec =0;
    T1.it_interval.tv_usec =t;
    setitimer (ITIMER_REAL, &T1, NULL);

    thread t1(Thread_Function);        
}

Problem is Function1 does not execute in other words I cant see Function1 on my output

Ss.unix
  • 43
  • 8

2 Answers2

1

From the setitimer manual page

A process has only one of each of the three types of timers.

You are trying to have two timers of the same type, this is not possible.

If you want to have multiple timers another solution is required.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Signals don't work well with threads.

They also don't work per thread but per process. What you are doing is first setting the SIGALRM signal handler to Function1 then you start a thread and you then overwrite the handler to call Function2 instead.

Even if you would have per-thread signal handler a signal is send to the whole process. So one random thread will handle the signal and all the other threads wont.

You can specify which thread you want to handle the signal with pthread_sigmask. But in general mixing signals and multithreading does not work well at all.

Here you have some similar questions which may shine a light on this more. They may talk about pthread instead of std::thread but the issues there are the same.

Signal handling in pthreads

POSIX threads and signals

Community
  • 1
  • 1
Hayt
  • 5,210
  • 30
  • 37
  • So ,you say signals and multithreading does not work well at all, What do you think about multiprocess? does it hep me? – Ss.unix Oct 19 '16 at 10:47
  • @Ss.unix it depends on what your goal is. Multiprocessing has it's advantages while threads also have theirs. But that is a whole other debate. – Hayt Oct 19 '16 at 10:51