【发布时间】:2012-03-09 05:50:09
【问题描述】:
重温这个问题:
我有多个线程正在运行(pthreads api),每个线程都有自己的计时器,在一定时间间隔后调用函数处理程序(int signum)。当这些线程调用处理程序和函数处理程序时,我怎么知道哪个线程调用了它?是否需要特定于线程的数据?
我注意到进入处理函数的线程与设置它的线程不同,因此调用 pthread_self() 不起作用。我该如何解决这个问题?
这是一个说明问题的小例子
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
void handler(int);
void call_alarm();
void *setup(void*);
pthread_t p;
void handler(int signum)
{
printf("handler thread %lu\n", pthread_self());
}
void call_alarm()
{
static struct itimerval timer;
static struct sigaction sa;
printf("call_alarm %lu\n", (unsigned long)pthread_self());
sa.sa_handler = handler;
sa.sa_flags = SA_RESETHAND;
timer.it_value.tv_usec = 500;
timer.it_value.tv_sec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
sigaction(SIGALRM, &sa, 0);
setitimer(ITIMER_REAL, &timer, 0);
}
void *setup(void *param)
{
while(1)
{
printf("caller thread %lu\n", pthread_self());
call_alarm();
pause();
}
}
int main(void)
{
if(pthread_create(&p, NULL, setup, NULL));
while(1);
return 0;
}
输出:
caller thread 3086637968
call_alarm 3086637968
handler thread 3086640832
如您所见,它会打印出不同的值。
【问题讨论】:
标签: c multithreading timer handler