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,
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;