多线程-临界资源(临界区)问题

临界区 表示一种公共资源或共享数据,可以被多个线程使用。但是每一次只能有一个线程使用它。一旦临界区资源被占用,想使用该资源的其他线程必须等待。

class TickerCenter{
    // 描述剩余的票的数量
    public static int restCount = 100;
}

上述程序的运行结果

运行结果分析:

线程1抢到了资源,并且已经做好了减法,但还没来得及输出,就被其他线程抢走了,等到线程1再次抢到资源时,才能完整输出上次的值.

临界资源问题解决方案:
线程访问临界资源时,加一把锁,其他线程再来访问这个资源的时候,看到锁,就不会再访问这个资源了,等到线程访问完成后,释放锁,其他资源才可以接着访问这个资源.

1) 同步代码段

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
临界区是指在多线程编程中,多个线程共享的临界资源对应的代码片段。例如,在一个银行存取款的场景中,假设有多个客户同时进行存取款操作,每个客户对应一个线程。为了保证数据的一致性和正确性,需要通过临界区来实现线程的互斥访问。 在C语言中,可以使用互斥锁(mutex)来实现临界区的互斥访问。互斥锁是一种同步机制,用于保护共享资源,确保同时只有一个线程可以访问临界区。下面是一个简单的银行存取款的示例: ``` #include <stdio.h> #include <pthread.h> int balance = 1000; // 银行账户余额 pthread_mutex_t mutex; // 互斥锁 void* deposit(void* arg) { pthread_mutex_lock(&mutex); // 上锁 int* amount = (int*)arg; balance += *amount; printf("存款 %d 元,余额为 %d 元\n", *amount, balance); pthread_mutex_unlock(&mutex); // 解锁 return NULL; } void* withdraw(void* arg) { pthread_mutex_lock(&mutex); // 上锁 int* amount = (int*)arg; if (balance >= *amount) { balance -= *amount; printf("取款 %d 元,余额为 %d 元\n", *amount, balance); } else { printf("余额不足\n"); } pthread_mutex_unlock(&mutex); // 解锁 return NULL; } int main() { pthread_t tid1, tid2; int amount1 = 500; int amount2 = 200; pthread_mutex_init(&mutex, NULL); // 初始化互斥锁 pthread_create(&tid1, NULL, deposit, &amount1); // 创建存款线程 pthread_create(&tid2, NULL, withdraw, &amount2); // 创建取款线程 pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_mutex_destroy(&mutex); // 销毁互斥锁 return 0; } ``` 在这个示例中,通过互斥锁mutex来保护临界资源balance。存款和取款操作都加了互斥锁,确保每次只有一个线程访问临界区。这样就避免了多个线程同时修改balance导致数据不一致的问题。最后,通过pthread_mutex_init()初始化互斥锁,pthread_mutex_lock()上锁,pthread_mutex_unlock()解锁,pthread_mutex_destroy()销毁互斥锁来完成对临界区的互斥访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值