建站提交历史文章,原文写作时间 2023 年 2 月前后。

锁与线程同步

互斥锁

互斥锁概述

  • 互斥锁mutex)即任一时刻最多允许一个线程独占资源。一把互斥锁最多被一个线程持有,持有互斥锁的线程具有访问和修改资源的权限,否则线程不应继续访问和修改相应资源,阻塞等待互斥锁释放或运行其他代码。
  • 互斥锁实际是对线程是否进入或阻塞在某段代码的控制,而此段代码所涉及的资源不是互斥锁关注的问题,是程序员应当考虑的问题。

互斥锁函数

  • man文档中找不到以下mutex相关函数。

  • pthread_mutex_initpthread_mutex_destroy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <pthread.h>
// initialize a mutex
// mutex:
// structure of mutex
// mutexattr:
// NULL is enough
// return value:
// return 0 for success, or non-zero errno on error
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);

// destroy a mutex
// you should call the function to destroy all the mutexes
// mutex:
// structure of mutex
// return value:
// return 0 for success, or non-zero errno on error
int pthread_mutex_destroy(pthread_mutex_t *mutex);
  • pthread_mutex_lockpthread_mutex_trylockpthread_mutex_unlock
1
2
3
4
5
6
7
#include <pthread.h>
// block to lock a mutex
int pthread_mutex_lock(pthread_mutex_t *mutex)
// try to lock a mutex non-blocked, return 0 on success or 16 if mutex is busy
int pthread_mutex_trylock(pthread_mutex_t *mutex)
// release a mutex
int pthread_mutex_unlock(pthread_mutex_t *mutex)

实际案例:窗口卖票

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int i = 1;
pthread_mutex_t mutex;

int done() {
pthread_mutex_lock(&mutex); // 上锁
int flag = i <= 100;
if (flag) {
printf("%ld\t%d\n", pthread_self(), i);
i++;
}
pthread_mutex_unlock(&mutex); // s
return flag;
}

void *sale(void *arg) {
while (done());
return NULL;
}

int main() {
pthread_mutex_init(&mutex, NULL); // 初始化互斥锁

pthread_t tid[3];
for (int i = 0; i < 3; i++) {
pthread_create(&tid[i], NULL, sale, NULL);
}
for (int i = 0; i < 3; i++) {
pthread_join(tid[i], NULL);
}

pthread_mutex_destroy(&mutex); // 销毁互斥锁
pthread_exit(NULL);

return 0;
}

读写锁

读写锁概述

  • 读写锁rwlock)分为读锁写锁,允许多线程持有读锁而只能有一个线程持有写锁写锁的优先级高于读锁
  • 读写锁允许多线程并发读取数据,但只能有一个线程

读写锁函数

  • man文档中找不到以下rwlock相关函数,与mutex用法相似,不作详细介绍。
  • pthread_rwlock_initpthread_rwlock_destroy
1
2
3
#include <pthread>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
  • pthread_rwlock_rdlockpthread_rwlock_tryrdlockpthread_rwlock_wrlockpthread_rwlock_trywrlockpthread_rwlock_unlock
1
2
3
4
5
6
#include <pthread>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); // read lock, blocked
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock); // read lock, non-blocked
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); // write lock, blocked
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock); // write lock, non-blocked
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock); // release the read and write lock

实际案例

敬请期待

死锁

敬请期待