pthread_mutex_lock函数与pthread_mutex_unlock是一般成对使用。pthread_mutex_lock与pthread_mutex_unlock之间代码不会被被别的进程中断。类似原子类的执行。
参考一下代码,当两个线程同时访问cnt时,会发生冲突。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define N 10
int cnt = 0;
void* thread_fun_0(void* arg) {
for (int i = 0; i < N; ++i) {
printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
++cnt;
usleep(100);
}
return NULL;
}
void* thread_fun_1(void* arg) {
for (int i = 0; i < N; ++i) {
printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
++cnt;
usleep(100);
}
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_fun_0, NULL);
pthread_create(&t2, NULL, thread_fun_1, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("cnt = %d (expect %d)\n", cnt, 2*N);
return 0;
}

每个线程是的cnt 递增10次,进程结束cnt应该是20。这次运行结果有问题,按理输出的cnt应该是1~20,不会重复。但是运行结果却重复了,这是因为对cnt更新时没有锁定系统。修改后代码如下:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define N 10
pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;
int cnt = 0;
void* thread_fun_0(void* arg) {
for (int i = 0; i < N; ++i) {
pthread_mutex_lock(&mux);
printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
++cnt;
pthread_mutex_unlock(&mux);
usleep(100);
}
return NULL;
}
void* thread_fun_1(void* arg) {
for (int i = 0; i < N; ++i) {
pthread_mutex_lock(&mux);
printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
++cnt;
pthread_mutex_unlock(&mux);
usleep(100);
}
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_fun_0, NULL);
pthread_create(&t2, NULL, thread_fun_1, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("cnt = %d (expect %d)\n", cnt, 2*N);
pthread_mutex_destroy(&mux);
return 0;
}

本次的运行结果很理想,没有出现冲突。
pthread互斥锁机制解析
886

被折叠的 条评论
为什么被折叠?



