# 跨进程同步与锁优化

在Android多进程架构中，进程间同步和锁机制是保证数据一致性和系统稳定性的关键技术。本文深入分析Android跨进程同步机制、锁优化策略和最佳实践。

## 进程同步架构概览

```mermaid
graph TB
    subgraph "同步原语"
        A1[互斥锁 Mutex] --> A2[条件变量 Condition]
        A2 --> A3[读写锁 RWLock]
        A3 --> A4[信号量 Semaphore]
        A4 --> A5[屏障 Barrier]
    end
    
    subgraph "跨进程同步"
        B1[文件锁] --> B2[共享内存]
        B2 --> B3[消息队列]
        B3 --> B4[信号量]
        B4 --> B5[Binder同步]
    end
    
    subgraph "优化策略"
        C1[锁粒度优化] --> C2[锁竞争避免]
        C2 --> C3[死锁预防]
        C3 --> C4[性能监控]
        C4 --> C5[自适应锁]
    end
```

## 1. 进程同步基础

### 1.1 同步原语分类
- **互斥锁（Mutex）**：保证同一时间只有一个线程访问共享资源
- **读写锁（RWLock）**：允许多个读线程同时访问，写线程独占访问
- **条件变量（Condition）**：线程等待特定条件满足
- **信号量（Semaphore）**：控制同时访问资源的线程数量
- **屏障（Barrier）**：等待多个线程到达同步点

### 1.2 Android中的同步机制
```cpp
// Android中的同步原语实现
class AndroidSync {
    // 1. Mutex实现
    class Mutex {
    private:
        pthread_mutex_t mMutex;
    public:
        Mutex() { pthread_mutex_init(&mMutex, NULL); }
        ~Mutex() { pthread_mutex_destroy(&mMutex); }
        void lock() { pthread_mutex_lock(&mMutex); }
        void unlock() { pthread_mutex_unlock(&mMutex); }
    };
    
    // 2. Condition实现
    class Condition {
    private:
        pthread_cond_t mCond;
        Mutex& mMutex;
    public:
        Condition(Mutex& mutex) : mMutex(mutex) {
            pthread_cond_init(&mCond, NULL);
        }
        void wait() { pthread_cond_wait(&mCond, &mMutex.mMutex); }
        void signal() { pthread_cond_signal(&mCond); }
        void broadcast() { pthread_cond_broadcast(&mCond); }
    };
    
    // 3. 读写锁实现
    class RWLock {
    private:
        pthread_rwlock_t mLock;
    public:
        RWLock() { pthread_rwlock_init(&mLock, NULL); }
        ~RWLock() { pthread_rwlock_destroy(&mLock); }
        void readLock() { pthread_rwlock_rdlock(&mLock); }
        void writeLock() { pthread_rwlock_wrlock(&mLock); }
        void unlock() { pthread_rwlock_unlock(&mLock); }
    };
};
```

## 2. 跨进程同步机制

### 2.1 文件锁（File Lock）
```cpp
// 文件锁实现跨进程同步
class FileLock {
private:
    int mFd;
    struct flock mLock;
    
public:
    FileLock(const char* filename) {
        // 打开文件
        mFd = open(filename, O_RDWR | O_CREAT, 0644);
        if (mFd < 0) {
            perror("open file failed");
        }
    }
    
    ~FileLock() {
        if (mFd >= 0) {
            close(mFd);
        }
    }
    
    // 获取排他锁
    bool lockExclusive() {
        mLock.l_type = F_WRLCK;    // 写锁（排他锁）
        mLock.l_whence = SEEK_SET;
        mLock.l_start = 0;
        mLock.l_len = 0;           // 锁定整个文件
        
        return fcntl(mFd, F_SETLKW, &mLock) != -1;
    }
    
    // 获取共享锁
    bool lockShared() {
        mLock.l_type = F_RDLCK;    // 读锁（共享锁）
        mLock.l_whence = SEEK_SET;
        mLock.l_start = 0;
        mLock.l_len = 0;
        
        return fcntl(mFd, F_SETLKW, &mLock) != -1;
    }
    
    // 释放锁
    bool unlock() {
        mLock.l_type = F_UNLCK;
        return fcntl(mFd, F_SETLK, &mLock) != -1;
    }
};
```

### 2.2 共享内存同步
```cpp
// 共享内存+信号量实现跨进程同步
class SharedMemorySync {
private:
    int mShmId;
    void* mShmAddr;
    sem_t* mSemaphore;
    
public:
    SharedMemorySync(const char* key, size_t size) {
        // 1. 创建共享内存
        key_t shmKey = ftok(key, 'R');
        mShmId = shmget(shmKey, size, 0644 | IPC_CREAT);
        
        // 2. 附加到进程地址空间
        mShmAddr = shmat(mShmId, NULL, 0);
        
        // 3. 创建信号量
        mSemaphore = sem_open(key, O_CREAT, 0644, 1);
    }
    
    ~SharedMemorySync() {
        // 分离共享内存
        shmdt(mShmAddr);
        // 关闭信号量
        sem_close(mSemaphore);
    }
    
    // 进入临界区
    void enterCriticalSection() {
        sem_wait(mSemaphore);  // P操作
    }
    
    // 离开临界区
    void leaveCriticalSection() {
        sem_post(mSemaphore);  // V操作
    }
    
    // 获取共享内存地址
    void* getSharedMemory() {
        return mShmAddr;
    }
};
```

### 2.3 Binder同步机制
```java
// Binder跨进程同步示例
public class BinderSyncService extends Service {
    private final Object mLock = new Object();
    private int mSharedValue = 0;
    
    private final IBinder mBinder = new ISyncService.Stub() {
        @Override
        public synchronized int getValue() {
            synchronized (mLock) {
                // 跨进程同步访问
                return mSharedValue;
            }
        }
        
        @Override
        public synchronized void setValue(int value) {
            synchronized (mLock) {
                // 跨进程同步修改
                mSharedValue = value;
                // 通知等待的线程
                mLock.notifyAll();
            }
        }
        
        @Override
        public synchronized void waitForValue(int target) throws RemoteException {
            synchronized (mLock) {
                while (mSharedValue != target) {
                    try {
                        // 跨进程等待
                        mLock.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    };
    
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}
```

## 3. 锁优化策略

### 3.1 锁粒度优化
```java
// 锁粒度优化示例
class LockGranularityOptimization {
    // 粗粒度锁 - 性能较差
    private final Object mCoarseLock = new Object();
    private Map<String, Integer> mData1 = new HashMap<>();
    private Map<String, String> mData2 = new HashMap<>();
    
    public void updateCoarse(String key, int value, String str) {
        synchronized (mCoarseLock) {  // 锁住所有数据
            mData1.put(key, value);
            mData2.put(key, str);
        }
    }
    
    // 细粒度锁 - 性能更好
    private final Object mLock1 = new Object();
    private final Object mLock2 = new Object();
    
    public void updateFine(String key, int value, String str) {
        synchronized (mLock1) {  // 只锁住相关数据
            mData1.put(key, value);
        }
        synchronized (mLock2) {
            mData2.put(key, str);
        }
    }
    
    // 读写锁优化
    private final ReentrantReadWriteLock mRwLock = new ReentrantReadWriteLock();
    
    public int readWithRWLock(String key) {
        mRwLock.readLock().lock();
        try {
            return mData1.getOrDefault(key, 0);
        } finally {
            mRwLock.readLock().unlock();
        }
    }
    
    public void writeWithRWLock(String key, int value) {
        mRwLock.writeLock().lock();
        try {
            mData1.put(key, value);
        } finally {
            mRwLock.writeLock().unlock();
        }
    }
}
```

### 3.2 锁竞争避免
```java
// 锁竞争避免策略
class LockCompetitionAvoidance {
    // 1. 锁分解（Lock Splitting）
    private final Object[] mLocks;
    private final Map<String, String>[] mDataSegments;
    
    public LockCompetitionAvoidance(int segments) {
        mLocks = new Object[segments];
        mDataSegments = new HashMap[segments];
        for (int i = 0; i < segments; i++) {
            mLocks[i] = new Object();
            mDataSegments[i] = new HashMap<>();
        }
    }
    
    // 根据key哈希选择锁
    private int getSegmentIndex(String key) {
        return Math.abs(key.hashCode()) % mLocks.length;
    }
    
    public void put(String key, String value) {
        int index = getSegmentIndex(key);
        synchronized (mLocks[index]) {
            mDataSegments[index].put(key, value);
        }
    }
    
    // 2. 锁粗化（Lock Coarsening）
    public void lockCoarseningExample() {
        // 不好的做法：多次加锁解锁
        synchronized (this) {
            operation1();
        }
        synchronized (this) {
            operation2();
        }
        synchronized (this) {
            operation3();
        }
        
        // 好的做法：锁粗化
        synchronized (this) {
            operation1();
            operation2();
            operation3();
        }
    }
    
    // 3. 无锁编程（Lock-Free）
    private final AtomicInteger mAtomicCounter = new AtomicInteger(0);
    
    public void lockFreeIncrement() {
        mAtomicCounter.incrementAndGet();
    }
    
    private final ConcurrentHashMap<String, String> mConcurrentMap = 
        new ConcurrentHashMap<>();
    
    public void lockFreePut(String key, String value) {
        mConcurrentMap.put(key, value);
    }
}
```

### 3.3 死锁预防与检测
```java
// 死锁预防策略
class DeadlockPrevention {
    // 1. 锁顺序一致
    private final Object mLockA = new Object();
    private final Object mLockB = new Object();
    
    public void safeMethod1() {
        // 总是先获取lockA，再获取lockB
        synchronized (mLockA) {
            synchronized (mLockB) {
                // 操作共享资源
            }
        }
    }
    
    public void safeMethod2() {
        // 保持相同的锁顺序
        synchronized (mLockA) {
            synchronized (mLockB) {
                // 操作共享资源
            }
        }
    }
    
    // 2. 锁超时机制
    public void lockWithTimeout() {
        ReentrantLock lock = new ReentrantLock();
        try {
            // 尝试获取锁，最多等待1秒
            if (lock.tryLock(1, TimeUnit.SECONDS)) {
                try {
                    // 执行操作
                } finally {
                    lock.unlock();
                }
            } else {
                // 获取锁超时，执行备用方案
                handleLockTimeout();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    // 3. 死锁检测
    public void deadlockDetection() {
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        long[] threadIds = threadBean.findDeadlockedThreads();
        
        if (threadIds != null) {
            ThreadInfo[] threadInfos = threadBean.getThreadInfo(threadIds);
            for (ThreadInfo threadInfo : threadInfos) {
                System.err.println("死锁检测到线程: " + threadInfo.getThreadName());
                System.err.println("  等待锁: " + threadInfo.getLockName());
                System.err.println("  被锁持有者: " + threadInfo.getLockOwnerName());
            }
            
            // 死锁恢复策略
            recoverFromDeadlock(threadInfos);
        }
    }
    
    private void handleLockTimeout() {
        // 锁超时处理逻辑
    }
    
    private void recoverFromDeadlock(ThreadInfo[] threadInfos) {
        // 死锁恢复逻辑，如中断线程、释放资源等
    }
}
```

## 4. 性能监控与调优

### 4.1 锁性能监控
```java
// 锁性能监控工具
class LockPerformanceMonitor {
    private final Map<String, LockStats> mLockStats = new ConcurrentHashMap<>();
    
    class LockStats {
        long acquireCount;
        long totalWaitTime;
        long maxWaitTime;
        long contentionCount;
        
        synchronized void recordAcquire(long waitTime) {
            acquireCount++;
            totalWaitTime += waitTime;
            maxWaitTime = Math.max(maxWaitTime, waitTime);
            if (waitTime > 10) { // 10ms视为竞争
                contentionCount++;
            }
        }
    }
    
    // 监控锁
    public <T> T monitorLock(String lockName, Supplier<T> task) {
        long startTime = System.currentTimeMillis();
        try {
            return task.get();
        } finally {
            long endTime = System.currentTimeMillis();
            long waitTime = endTime - startTime;
            
            LockStats stats = mLockStats.computeIfAbsent(
                lockName, k -> new LockStats());
            stats.recordAcquire(waitTime);
        }
    }
    
    // 生成性能报告
    public void generateReport() {
        for (Map.Entry<String, LockStats> entry : mLockStats.entrySet()) {
            LockStats stats = entry.getValue();
            if (stats.acquireCount > 0) {
                double avgWaitTime = (double) stats.totalWaitTime / stats.acquireCount;
                double contentionRate = (double) stats.contentionCount / stats.acquireCount;
                
                System.out.println(String.format(
                    "锁[%s]: 获取次数=%d, 平均等待=%.2fms, 最大等待=%dms, 竞争率=%.2f%%",
                    entry.getKey(), stats.acquireCount, avgWaitTime,
                    stats.maxWaitTime, contentionRate * 100));
            }
        }
    }
}
```

### 4.2 自适应锁优化
```java
// 自适应锁策略
class AdaptiveLockStrategy {
    private final ReentrantLock mLock = new ReentrantLock();
    private volatile int mContentionLevel = 0;
    private volatile long mLastContentionTime = 0;
    
    // 自适应获取锁
    public void adaptiveLock(Runnable task) {
        if (shouldUseSpinLock()) {
            // 使用自旋锁（低竞争场景）
            spinLock(task);
        } else {
            // 使用阻塞锁（高竞争场景）
            blockingLock(task);
        }
        
        updateContentionLevel();
    }
    
    private boolean shouldUseSpinLock() {
        long currentTime = System.currentTimeMillis();
        // 如果最近有竞争，使用阻塞锁
        if (currentTime - mLastContentionTime < 1000) {
            return false;
        }
        // 低竞争级别使用自旋锁
        return mContentionLevel < 3;
    }
    
    private void spinLock(Runnable task) {
        int spinCount = 0;
        while (!mLock.tryLock()) {
            if (++spinCount > 100) {
                // 自旋次数过多，转为阻塞
                mLock.lock();
                break;
            }
            // 短暂自旋
            Thread.yield();
        }
        
        try {
            task.run();
        } finally {
            mLock.unlock();
        }
    }
    
    private void blockingLock(Runnable task) {
        mLock.lock();
        try {
            task.run();
        } finally {
            mLock.unlock();
        }
    }
    
    private void updateContentionLevel() {
        // 根据锁竞争情况更新竞争级别
        if (mLock.hasQueuedThreads()) {
            mContentionLevel++;
            mLastContentionTime = System.currentTimeMillis();
        } else if (mContentionLevel > 0) {
            mContentionLevel--;
        }
    }
}
```

## 5. 调试与问题排查

### 5.1 锁问题调试工具
```bash
# 查看线程锁状态
adb shell dumpsys activity processes | grep -A 20 "locked"
adb shell ps -T | grep -E "(blocked|waiting)"

# 性能分析
adb shell am dumpheap <pid> /data/local/tmp/heap.hprof
adb shell am profile start <pid> /data/local/tmp/trace.trace

# systrace分析锁竞争
python systrace.py --time=10 -o trace.html sched freq idle am wm gfx view sync
```

### 5.2 常见问题与解决方案
- **死锁问题**：使用锁顺序一致、锁超时机制、死锁检测工具
- **锁竞争严重**：优化锁粒度、使用读写锁、减少锁持有时间
- **性能瓶颈**：监控
