互斥算法-peterson解法

影子 09:00:31
#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>

bool flag[2] = {false, false};
int turn = 0;
int sharedVariable = 0;

void* process0(void* arg) {
    while (true) {
        flag[0] = true;
        turn = 1;

        while (flag[1] && turn == 1) {
            // 等待进入临界区域
        }

        // 进入临界区域,访问共享资源
        sharedVariable++;
        printf("Process 0: sharedVariable = %d\n", sharedVariable);

        flag[0] = false;

        // 执行剩余的代码
        // ...
    }
}

void* process1(void* arg) {
    while (true) {
        flag[1] = true;
        turn = 0;

        while (flag[0] && turn == 0) {
            // 等待进入临界区域
        }

        // 进入临界区域,访问共享资源
        sharedVariable--;
        printf("Process 1: sharedVariable = %d\n", sharedVariable);

        flag[1] = false;

        // 执行剩余的代码
        // ...
    }
}

int main() {
    pthread_t thread0, thread1;

    // 创建两个线程,分别执行进程P0和P1的代码
    pthread_create(&thread0, NULL, process0, NULL);
    pthread_create(&thread1, NULL, process1, NULL);

    // 主线程等待子线程结束
    pthread_join(thread0, NULL);
    pthread_join(thread1, NULL);

    return 0;
}

 

这个思想是设置一个公共锁和线程私有锁。

当公共锁和私有锁都被占用时,表示临界资源被其他线程使用,只能等待。

posted @ 2023-05-19 09:29  愿得入睡  阅读(35)  评论(0编辑  收藏  举报