更新时间:2021-09-10 09:29:44
假设 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;