Saturday, December 4, 2010

Signals Not Working with threads

Here is small problem which i would like to share

1 #include
2 #include
3 #include
4 #include
5
6 //volatile int i = 0;
7 int i = 0;
8
9 //res = l;\
10 res = (l && l++); \
11
12 #define COND(l, x, res) \
13 pthread_mutex_lock(x);\
14 res = (l==0?l++:l && l++); \
15 pthread_mutex_unlock(x);
16
17 #define MSG_START "Message Start %s .. 0x%x\n", __func__
18 #define MSG_END "Message End %s .. 0x%x\n", __func__
19
20 void *thread(void *p1);
21 inline void CatchInterrupt (int signum)
22 {
23 /* there is no need to lock any variable in the signal handler
24 * the current context of the process is freezed and the execuation
25 * is set in the signal handler
26 */
27 i = 0;
28 }
29 void *thread(void *p1)
30 {
31 unsigned int res;
32 pthread_mutex_t *p = p1;
33 printf(MSG_START, pthread_self());
34 do{ /* Tight Loop */
35 COND(i, p, res);
36 }while(res);
37 printf(MSG_END, pthread_self());
38 return NULL;
39 }
40 int main()
41 {
42 const pthread_mutexattr_t *attr __attribute__((restrict));
43 attr = NULL;
44 pthread_t tid1 = 0;
45 pthread_t tid2 = 0;
46 pthread_t tid3 = 0;
47 pthread_t tid4 = 0;
48 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
49 i++;
50 signal(SIGINT, CatchInterrupt);
51 pthread_mutex_init(&mutex, attr);
52 pthread_create(&tid1, attr, thread, &mutex);
53 pthread_create(&tid2, attr, thread, &mutex);
54 pthread_create(&tid3, attr, thread, &mutex);
55 pthread_create(&tid4, attr, thread, &mutex);
56 pthread_join(tid1, NULL);
57 pthread_join(tid2, NULL);
58 pthread_join(tid3, NULL);
59 pthread_join(tid4, NULL);
60 pthread_mutex_destroy(&mutex);
61 return 0;
}

Compile this with gcc, mine version was
gcc version 4.1.2 20070925 (Red Hat 4.1.2-33) Thread Model - posix

When run, I need to give 4 SIGINT to kill the process, But when we change the

line

res = (l && l++); \
with
res = (l==0?l++:l && l++); \

I need to give 1 SIGINT to this process ID, this should be correct behavior,

Can any one share what is reason.