この質問に再訪する:どのスレッドがタイマーハンドラを設定しているかを示しますか?
私は複数のスレッドを実行しています(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
を。
+1。 ['gettid'対' pthread_self']の詳細(http://stackoverflow.com/a/6372351/298054)。 – jweyrich
これは元の質問に答えていません。タイマーの現在の実装を使用する必要があります。私はちょうどpthreadsを使用してハンドラを呼び出すスレッドを知りたい。 – Lucas