编辑代码

let n: Int = 10; // 假设有10个缓冲区
let bufferPool: [Int] = [1, 0, 2, 10, 5, 6, 7, 1, 0, 10] // 假设缓冲区的容量为10 缓冲池中两个空的,两个满的
var mutex: Int = 1; // mutex=互斥 互斥信号量 用来控制互斥访问缓冲池 一个标记 代表临界区有进程了
var full: Int = 0; // 缓冲池中有多少个缓冲区满了
var empty: Int = n; // 缓冲池中有多少个缓冲区空了

var data: Int = 0; // 生产者生产的数据 = 消息

// 生产者进程
func producer() {
    while true {
        data = data + 1; //生产数据
        var emptyBuffers: [Int] = getEmptyBuffer(empty: empty);
        mutex = 1; // P(mutex) 进入临界区 = 访问临界资源 然后标志临界区有进程 就是上互斥锁
        
    }
}

// 从缓冲池中获取空的缓冲区 的索引
func getEmptyBuffer(empty: Int) -> [Int] {
    var indexs: [Int] = [];
    for index in 0 ..< bufferPool.count {
        if arr[index] == 0 {
            indexs.append(index);
        }
    }
    return [Int](repeating: 0, count: empty);
}

var arr: [Int] = getEmptyBuffer(empty: empty);
for item in arr {
    print(item);
}