在C语言中断驱动的环境中共享主线程和从线程之间的数据 [英] Sharing data between master thread and slave thread in interrupt driven environment in C

查看:107
本文介绍了在C语言中断驱动的环境中共享主线程和从线程之间的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

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
}

目前,我用下面的启动在f2的结构():

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

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

然后我传递一个指针的共享以线程。然后线程更新的共享周期性。然后F2()就会知道,如果日()的基础上的要素已经开始的共享并会通过读取检查日()的状态的共享

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.

让我们假设的要素之一的共享是互斥来提供线程安全。这是一个很好的解决方案?是否有这样做的更优雅的方式?我已经测试了code和它的作品。我只是需要一些专家的意见在这里。

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.

谢谢,

推荐答案

假设 F2()使用在同一个互斥体的共享结构来读取线程使用修改数据的数据前锁定,我看不出有什么问题。

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.

如果你有多个线程调用 F2(),您可能需要使用读写锁的线程状态读取和写入。互斥仍然可以用于序列化线程创建检查。你也可以使用 pthread_rwlock_wrlock()连载创作,但code可以说是不太清楚。

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.

使用互斥锁序列化创建F2(

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;

使用读写锁将序列号创建F2(

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;

这篇关于在C语言中断驱动的环境中共享主线程和从线程之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆