在多线程程序中在哪里定义互斥锁,有什么区别
Where to define a mutex in a multithread program and what is the difference
我是多线程编程的新手,我对在哪里声明互斥锁感到困惑。通过大量谷歌搜索,我得到了互斥锁 lock/unlock 的想法。但是我仍然不知道我需要在哪里声明pthread_mutex_t
变量,有什么区别。
例如这里是案例 1:
#include <pthread.h>
pthread_mutex_t count_mutex;
long long count;
void
increment_count()
{
pthread_mutex_lock(&count_mutex);
count = count + 1;
pthread_mutex_unlock(&count_mutex);
}
这是案例 2:
struct order_que
{
struct order **orders;
int size;
int head;
int tail;
pthread_mutex_t lock;
};
void *ClientThread(void *arg)
{
struct client_arg *ca = (struct client_arg *)arg;
int i;
for(i=0; i < ca->order_count; i++) {
......
queued = 0;
while(queued == 0) {
pthread_mutex_lock(&(ca->order_que->lock));
......
if(next == ca->order_que->tail) {
pthread_mutex_unlock(&(ca->order_que->lock));
continue;
}
......
pthread_mutex_unlock(&(ca->order_que->lock));
......
}
}
return(NULL);
}
谁能告诉我这两种情况有什么区别以及为什么我需要以这种方式声明互斥量?
Could anyone tell me what's the difference between these two cases and why I need declare the mutex in this way?
一般来说,互斥量被设计成synchronize accesses (protect against race conditions)到资源。因此,互斥锁声明通常遵循它要保护的资源的声明。
在案例 #1 中,互斥体同步访问全局变量 count
- 因此它与变量一起被全局声明。它保证,当 increment_count()
在不同 CPU 上从不同线程调用时,count
变量上的非原子算术将以一致的方式执行,产生预期结果。
在案例 #2 中,互斥锁同步访问 order_que
ring buffer ,(显然)可以从多个线程访问。 (似乎是作业队列的代码:items/jobs/etc 的队列,线程应该并行处理。)通用环形缓冲区需要对 head
和 tail
指针进行运算才能入队和出列项目。为了保证 head
/tail
上的算术结果一致(您的示例中缺少),互斥锁用于同步对它们的访问。因此,互斥锁在与变量相同的上下文中声明。
我是多线程编程的新手,我对在哪里声明互斥锁感到困惑。通过大量谷歌搜索,我得到了互斥锁 lock/unlock 的想法。但是我仍然不知道我需要在哪里声明pthread_mutex_t
变量,有什么区别。
例如这里是案例 1:
#include <pthread.h>
pthread_mutex_t count_mutex;
long long count;
void
increment_count()
{
pthread_mutex_lock(&count_mutex);
count = count + 1;
pthread_mutex_unlock(&count_mutex);
}
这是案例 2:
struct order_que
{
struct order **orders;
int size;
int head;
int tail;
pthread_mutex_t lock;
};
void *ClientThread(void *arg)
{
struct client_arg *ca = (struct client_arg *)arg;
int i;
for(i=0; i < ca->order_count; i++) {
......
queued = 0;
while(queued == 0) {
pthread_mutex_lock(&(ca->order_que->lock));
......
if(next == ca->order_que->tail) {
pthread_mutex_unlock(&(ca->order_que->lock));
continue;
}
......
pthread_mutex_unlock(&(ca->order_que->lock));
......
}
}
return(NULL);
}
谁能告诉我这两种情况有什么区别以及为什么我需要以这种方式声明互斥量?
Could anyone tell me what's the difference between these two cases and why I need declare the mutex in this way?
一般来说,互斥量被设计成synchronize accesses (protect against race conditions)到资源。因此,互斥锁声明通常遵循它要保护的资源的声明。
在案例 #1 中,互斥体同步访问全局变量 count
- 因此它与变量一起被全局声明。它保证,当 increment_count()
在不同 CPU 上从不同线程调用时,count
变量上的非原子算术将以一致的方式执行,产生预期结果。
在案例 #2 中,互斥锁同步访问 order_que
ring buffer ,(显然)可以从多个线程访问。 (似乎是作业队列的代码:items/jobs/etc 的队列,线程应该并行处理。)通用环形缓冲区需要对 head
和 tail
指针进行运算才能入队和出列项目。为了保证 head
/tail
上的算术结果一致(您的示例中缺少),互斥锁用于同步对它们的访问。因此,互斥锁在与变量相同的上下文中声明。