我该如何处理不同位置的共享变量?
void dequeue ()
{
QITEM *qKill = qHead;
.
.
.
#pragma omp critical
qHead = qHead->qNext;
free(qKill);
}
void enqueue (int iNode, int iDist, int iPrev)
{
.
.
.
QITEM *qLast = qHead;
#pragma omp critical
{
while (qLast->qNext) qLast = qLast->qNext;
qLast->qNext = qNew;
}
}
我知道如果只有一个线程可以访问入队和出队中的临界区。
但是,如果一个线程正在访问入队中的关键部分,而另一个线程正在访问出队中的关键部分,那么这段代码是否正确保护了共享列表?
qHead 是指向链表头部的指针。
void dequeue ()
{
QITEM *qKill = qHead;
.
.
.
#pragma omp critical
qHead = qHead->qNext;
free(qKill);
}
void enqueue (int iNode, int iDist, int iPrev)
{
.
.
.
QITEM *qLast = qHead;
#pragma omp critical
{
while (qLast->qNext) qLast = qLast->qNext;
qLast->qNext = qNew;
}
}
I know that if only one thread can access the critical section in enqueue and dequeue.
However, if one thread is accessing the critical section in enqueue and the other thread is accessing the critical section in dequeue then is this code protecging the shared list properly?
qHead is a pointer to the head of the linked list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的代码中,您使用 OpenMP 中的未命名关键部分,这是全局且唯一的关键部分。因此,只有一个线程可以进入代码中的关键部分。要回答你的问题,是的,你不需要担心互斥性,因为只有一个锁。
为了在 OpenMP 中使用多个锁,请在
ritic
pragma 中使用名称。http://software.intel.com/en- us/articles/more-work-sharing-with-openmp/
一个示例是
#pragma omp critical(maxvalue)
。然而,很明显,拥有多个锁会增加死锁、数据竞争、锁护送和任何类型的并发错误的可能性。
In your code, you are using unnamed critical section in OpenMP, which is the global and unique critical section. So, only a single thread can enter the section of the critical sections in your code. To answer your question, yes you don't need to worry about the mutual exclusiveness as there is a single lock.
In order to use multiple locks in OpenMP, please use a name in
critical
pragma.http://software.intel.com/en-us/articles/more-work-sharing-with-openmp/
An example would be
#pragma omp critical(maxvalue)
.However, it is obvious that having multiple locks will increase the possibility of dead locks, data races, lock convoying, and any kinds of concurrency bugs.