互斥锁并不能保证任务不能被调度

 互斥锁不能保证在临界区的时候,不发送任务调度,所以为了保护共享的资源不被调度访问,需要在两个线程都加互斥锁来保证任务不调度

#include <stdio.h>
#include <pthread.h>
#include <unistd.h> 

int shared_resource = 0;

pthread_mutex_t mutex;

void *thread_function(void *arg)
{
    while (1)
    {
        printf("0\n");
        pthread_mutex_lock(&mutex);
        printf("1\n");
        sleep(2);
        printf("2\n");
        pthread_mutex_unlock(&mutex);
        printf("3\n");
    }

    pthread_exit(NULL);
}
void *thread_function1(void *arg)
{

    while (1)
    {
        printf("thread_function1\n");
        sleep(1);
    }
    pthread_exit(NULL);
}

int main()
{
    pthread_t threads[2];

    pthread_mutex_init(&mutex, NULL);

    int result = pthread_create(&threads[0], NULL, thread_function, NULL);
    int result1 = pthread_create(&threads[1], NULL, thread_function1, NULL);

    for (int i = 0; i < 2; i++)
    {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&mutex);

    return 0;
}

运行结果如下:

在多线程环境中,只有当一个线程持有互斥锁并进入临界区时,其他线程才会被阻塞,直到该锁被释放。因此,在你的代码中,即使 thread_function 获取到了 mutex 互斥锁并进入临界区,thread_function1 仍然可以被任务调度器调度并运行,因为它没有尝试获取 mutex 锁。

所以,即使 thread_function 正在执行临界区操作,thread_function1 也可以被调度器执行,因为它不受 mutex 的影响,没有在临界区内等待互斥锁。

我确认一下:在你的代码中,虽然 thread_function 使用了互斥锁来保护临界区(即共享资源的访问),而 thread_function1 没有使用任何互斥手段。这意味着以下情况可能发生:

  1. 调度行为:thread_function 获取到互斥锁 mutex 并进入临界区时,它会阻止其他尝试获取同一 mutex 的线程(如其他 thread_function 实例或其他使用 mutex 的线程)进入临界区。这是互斥锁的基本特性,确保在任意时刻只有一个线程可以访问共享资源。

  2. 未受影响的线程: thread_function1 没有获取 mutex 锁,因此它不受 mutex 的保护或阻塞。这意味着即使 thread_function 正在执行其临界区代码,thread_function1 也可以由调度器选择执行,因为它不需要等待或竞争 mutex 锁。

综上所述,即使 thread_function 正在使用互斥锁保护共享资源,thread_function1 仍然可以在 thread_function 执行临界区时被调度执行。这是因为 thread_function1 没有与 mutex 相关联,不会被 mutex 的锁定状态所阻塞。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文武先生hh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值