【发布时间】:2021-12-14 06:29:33
【问题描述】:
我想将一些东西添加到我的列表中,如果列表中已经存在某些内容,我想在重新添加之前将其删除。这只是我自己尝试的一个练习(我知道,做这样的事情没有实际目的)
spin_lock(&mylock);
bool added = false
list_for_each_entry_safe(cur, nxt, &mylist.entries, entries)
{
//Check to see if cur == the item I want to add, if it is add it and set my bool to true
}
//Check to see if my bool is true. If it's false, add the item to the list
spin_unlock(&mylock);
这不安全吗?问题是我无法弄清楚如何在不创建竞争条件的情况下将自旋锁放在其他任何地方。例如,如果我这样做了
list_for_each_entry_safe(cur, nxt, &mylist.entries, entries)
{
spin_lock(&mylock);
//Check to see if cur == the item I want to add, if it is add it and set my bool to true
spin_unlock(&mylock);
}
//race condition here
spin_lock(&mylock);
//Check to see if my bool is true. If it's false, add the item to the list
spin_unlock(&mylock);
可能存在竞争条件,我在此处注释了“竞争条件”,因为其他一些线程可以添加该项目,然后我不知道,当前线程会再次添加该项目,所以会有重复列表中的项目。
问题是我不知道在自旋锁的关键部分内是否可以有整个 list_for_each_entry?
【问题讨论】:
标签: c multithreading concurrency linux-kernel spinlock