如何在线程之间进行同步,其中一个是使用pthread的计时器?

时间:2014-02-13 06:12:50

标签: c multithreading pthreads mutex semaphore

我想用3个线程创建一个进程。其中,我想要一个线程每50ms工作一次。所以做了2个线程来完成我的其他工作,在第三个线程中我初始化了一个计时器。当我这样做时,线程之间的同步似乎很好。我找不到每50ms执行一次的定时器代码。它的性质随意。代码简介如下所示。提前谢谢。

void * vUserInterfaceThread()
{
    while(1)
    {
        //***doing my interface code here***********/
    }
}
void * vMornitorThread()
{
    while(1)
    {
        //***doing my monitor code here***********/
    }
}
void * vTimerThread()
{
    vStartTimer(ENABLE); // enabled the timer with 50ms delay with the function 
     while(1);
}
void vTimerFunction()
{
    //******Code to be executed in every  50ms time duration here************//
}
void vStartTimer(unsigned char ucValue)
{
    if(ucValue == ENABLE)
    {
        memset (&sSigActionStruct, 0, sizeof (sSigActionStruct));
        sSigActionStruct.sa_handler = &vTimerHandler;
        sigaction (SIGVTALRM, &sSigActionStruct, NULL);

        iTimerValue.it_value.tv_sec = 0;
        iTimerValue.it_value.tv_usec = TIMERLOADVALUE; //Load value for 50ms

        iTimerValue.it_interval.tv_sec = 0;
        iTimerValue.it_interval.tv_usec = TIMERLOADVALUE; //Load value for 50ms
        setitimer (ITIMER_VIRTUAL/*ITIMER_REAL*/, &iTimerValue, NULL);
    }
}

int main(void)
{
    //***************doing other initialisations***************************//
        pthread_create(&pThreadID1,NULL,vUserInterfaceThread,NULL);
        pthread_create(&pThreadID2,NULL,vMornitorThread,NULL);
        pthread_create(&pThreadID3,NULL,vTimerThread,NULL);
        pthread_join(pThreadID1,NULL);
        pthread_join(pThreadID2,NULL);
        pthread_join(pThreadID3,NULL);
}

1 个答案:

答案 0 :(得分:2)

回答你问题的一部分:

如果您想调整线程优先级,可以使用pthread_attr_setschedparam

pthread_attr_t thread_attributes;
pthread_attr_init(&thread_attributes);
struct sched_param params = {.sched_priority = 15}; // Set higher/lower priorities in other threads
pthread_attr_setschedparam(&thread_attributes, &params);
pthread_create(&pThreadID1, &thread_attributes, vUserInterfaceThread, NULL);