非分布式锁中几种比较常见的锁
互斥锁,锁粒度大,未获得锁后,线程休眠,进入waiting队列,sleep-wait
try_lock, 尝试加锁,非阻塞,获取不到锁后,会返回非0,适用于获取不到锁后可以进行其他操作的场景
自旋锁,不休眠,busy-wait,不停请求得到锁,不休眠不切换上下文,自旋锁的效率远高于互斥锁,不足在于自旋锁一直占用着CPU,他在未获得锁的情况下,一直运行(自旋),所以占用着CPU,如果不能在很短的时间内获得锁,这无疑会使CPU效率降低。在用自旋锁时有可能造成死锁,当递归调用时有可能造成死锁,调用有些其他函数也可能造成死锁,如 copy_to_user()、copy_from_user()、kmalloc()等。
因此我们要慎重使用自旋锁,自旋锁只有在内核可抢占式或SMP的情况下才真正需要,在单CPU且不可抢占式的内核下,自旋锁的操作为空操作(等到时间片耗尽,单核上不会说真的就死锁了)。自旋锁适用于锁使用者保持锁时间比较短的情况下,临界区比较小,很快就执行完毕的时候。
读写锁粒度更小,采用读写锁,则可以在任一时刻允许多个读出者存在
之前的加锁操作目的是控制临界区
原子操作,可以将++对应的三条指令原子成一条来执行。注意__asm__ volatile和volatile关键字不同,volatile关键字只保证顺序性(不做指令顺序优化,按序执行)和可见性(用内存不用缓存),并不能保证非原子操作时带来的问题。asm volatile带来了原子性,不可再分的语句,保证了线程安全。
共享内存在不同进程中访问时,原子操作仍然可以保证。如果是子父进程的话,锁还可以生效(fork创建的子进程会拷贝父进程的代码段、数据段、静态数据段、堆、栈、IO缓冲区),但是要注意ATFORK() --同步父子进程 PTHREAD_MUTEX_LOCK加解锁问题父进程先开启一个子线程,子线程中调用pthread_mutex_lock。再fork子进程,子进程同样调用pthread_mutex_lock ,导致的死锁问题
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>
#define THREAD_SIZE 10
int count = 0;
pthread_mutex_t mutex;
pthread_spinlock_t spinlock;
pthread_rwlock_t rwlock;
// MOV dest, src; at&t
// MOV src, dest; x86
int inc(int *value, int add) {
int old;
__asm__ volatile (
"lock; xaddl %2, %1;" // "lock; xchg %2, %1, %3;"
: "=a" (old)
: "m" (*value), "a" (add)
: "cc", "memory"
);
return old;
}
//
void *func(void *arg) {
int *pcount = (int *)arg;
int i = 0;
while (i++ < 100000) {
#if 0
(*pcount) ++;
#elif 0
pthread_mutex_lock(&mutex);
(*pcount) ++;
pthread_mutex_unlock(&mutex);
#elif 0
if (0 != pthread_mutex_trylock(&mutex)) {
i --;
continue;
}
(*pcount) ++;
pthread_mutex_unlock(&mutex);
#elif 0
pthread_spin_lock(&spinlock);
(*pcount) ++;
pthread_spin_unlock(&spinlock);
#elif 0
pthread_rwlock_wrlock(&rwlock);
(*pcount) ++;
pthread_rwlock_unlock(&rwlock);
#else
inc(pcount, 1);
#endif
usleep(1);
}
}
int main() {
#if 0
pthread_t threadid[THREAD_SIZE] = {0};
pthread_mutex_init(&mutex, NULL);
pthread_spin_init(&spinlock, PTHREAD_PROCESS_SHARED);
pthread_rwlock_init(&rwlock, NULL);
int i = 0;
int count = 0;
for (i = 0;i < THREAD_SIZE;i ++) {
int ret = pthread_create(&threadid[i], NULL, func, &count);
if (ret) {
break;
}
}
for (i = 0;i < 100;i ++) {
pthread_rwlock_rdlock(&rwlock);
printf("count --> %d\n", count);
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
#else
int *pcount = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0);
int i = 0;
pid_t pid = 0;
for (i = 0;i < THREAD_SIZE;i ++) {
pid = fork();
if (pid <= 0) {
usleep(1);
break;
}
}
if (pid > 0) { //
for (i = 0;i < 100;i ++) {
printf("count --> %d\n", (*pcount));
sleep(1);
}
} else {
int i = 0;
while (i++ < 100000) {
#if 0
(*pcount) ++;//出问题
#else
inc(pcount, 1);//多进程下的cas操作
#endif
usleep(1);
}
}
#endif
}
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "unistd.h"
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
sleep(2);
// Wait until main() sends data
std::unique_lock lk(m);
//cv.wait(lk, []{return ready;});
cv.wait(lk);
// after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";
// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
//cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
// send data to the worker thread
//sleep(2);
{
std::lock_guard lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
// wait for the worker
{
std::unique_lock lk(m);
cv.wait(lk, []{return processed;});
}
std::cout << "Back in main(), data = " << data << '\n';
worker.join();
}