Sharing data between master thread and slave thread in interrupt driven environment in C

和自甴很熟 提交于 2019-12-13 18:23:47

问题


I have the following:

f1()
{
    while(1)
    {
        call f(2) if hardware interrupt pin goes high
    }
}

f2()
{
    if( th() not started )
    {
        start thread th()
    }
    else
    {
        return thread th() status
    }
}

th()
{
    time-consuming operation
}

At the moment, I use the following to initiate a struct in f2():

static struct SharedData shared;
if( shared == NULL)
{
    initialize shared
}

Then I pass a pointer to shared to the thread. The thread then updates shared periodically. f2() will then know if th() has been started based on elements of shared and it will check the status of th() by reading from shared.

Let's assume one of the elements of shared is a mutex to provide thread safety. Is this a good solution? Is there a more elegant way of doing this? I have tested the code and it works. I just need some expert advice here.

Thanks,


回答1:


Assuming that f2() uses the same mutex in the shared structure to lock before reading the data that the thread th uses to modify the data, I don't see any issues.

If you have more than one thread calling f2(), you may want to use a read-write lock for reading and writing of the thread status of th. The mutex could still be used to serialize the thread creation check. You could also use a pthread_rwlock_wrlock() to serialize th creation, but the code is arguably less clear.

Using a mutex to serialize th creation in f2():

pthread_rwlock_rdlock(&shared.rwlock);
result = shared.th_status;
if (! shared.th_created) {
    pthread_mutex_lock(&shared.mutex);
    if (! shared.th_created) {
        pthread_create(...);
        shrared.th_created = 1;
    }
    pthread_mutex_unlock(&shared_mutex);
}
pthread_rwlock_unlock(&shared.rwlock);
return result;

Using the read-write lock to serialize th creation in f2():

pthread_rwlock_rdlock(&shared.rwlock);
result = shared.th_status;
if (! shared.th_created) {
    pthread_rwlock_unlock(&shared.rwlock);
    pthread_rwlock_wrlock(&shared.rwlock);
    if (! shared.th_created) {
        pthread_create(...);
        shrared.th_created = 1;
    }
}
pthread_rwlock_unlock(&shared.rwlock);
return result;


来源:https://stackoverflow.com/questions/17350416/sharing-data-between-master-thread-and-slave-thread-in-interrupt-driven-environm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!