重新审视这个问题:
我有多个线程正在运行(pthreads api),每个线程都有自己的计时器,在一定的时间间隔后调用函数处理程序(intsignum)。当这些线程调用处理程序并在函数处理程序内时,我如何知道哪个线程调用了它?是否需要特定于线程的数据?
我注意到进入处理函数的线程与设置它的线程是不同的线程,因此调用 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
正如您所看到的,它打印出不同的值。
最佳答案
您可以在调用处理程序时打印线程 ID:
如果不能,请在处理程序周围编写一个函数包装器,并告诉您的代码调用包装器函数,而不是直接调用处理程序。
关于c - 指示哪个线程设置计时器处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9334863/