微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在线程之间共享的回调函数中是否需要互斥锁?

如何解决在线程之间共享的回调函数中是否需要互斥锁?

我使用 linux posix 计时器模块(timer_create/timer_settime 等)实现了简单的单次/定期计时器。我使用 sigevent 结构将回调函数指定为通知函数。由于我对两个线程使用相同的回调函数(尽管我没有共享任何全局数据),我是否需要在回调函数添加互斥锁?下面附上我的 main.c 代码

void callback_func(union sigval sigev_value)
{
    time_t rawtime;
    struct tm * timeinfo;
 
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );  
    myTimerCallbackContext_t *timer_info = sigev_value.sival_ptr;
    if (timer_info->id)
    {
        fprintf(stdout,"Callback for timer %d %s\n",timer_info->id,asctime(timeinfo));
    }     
}
uint32_t create_timer(myTimerData_t * timer_info)
{
    uint32_t result = TIMER_ERR_OK;
    result = myTimerStart(timer_info);
    
    if (result != TIMER_ERR_OK)
    {
        fprintf(stdout,"Start timer Failed \n");
    }
    return result;
}
 
int main()
{
    myTimerCallback_f *fun_p = callback_func;
    myTimerCallbackContext_t context_timer1,context_timer2;
    context_timer1.id = 1;
    context_timer2.id = 2;
    uint32_t result;
 
    myTimerData_t one_shot = {1000,1,NULL,fun_p,&context_timer1,TIMER_NOTSTARTED};
    myTimerData_t periodic = {1000,&context_timer2,TIMER_NOTSTARTED};
    int32_t remainingTime;
 
 
    result = create_timer(&one_shot);
    if (result == TIMER_ERR_OK)
    {
        fprintf(stdout,"Created single shot timer %dms \n",one_shot.intervalInMs);
    }
    
    result = create_timer(&periodic);
    if (result == TIMER_ERR_OK)
    {
        fprintf(stdout,"Created periodic timer %dms \n",periodic.intervalInMs);
    }
 
    result = myTimerStop(&one_shot);
    if (result == TIMER_ERR_OK)
    {
        fprintf(stdout,"Stopped one shot timer %dms \n",one_shot.intervalInMs);
    }
    result = myTimerStop(&periodic);
    if (result == TIMER_ERR_OK)
    {
        fprintf(stdout,"Stopped periodic timer %dms \n",periodic.intervalInMs);
    }
 
    return 0;
 }

提前致谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。