linux c 多线程互斥锁

beers.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

int beers = 2000000;
// 创建互斥锁,互斥锁对所有可能发生冲突的线程可见,是一个全局变量.
// PTHREAD_MUTEX_INITIALIZER实际上是一个宏,当编译器看到它,就会插入创建互斥锁的代码
pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER;

void* drink_lots_1(void* a) {
    int i;

    pthread_mutex_lock(&beers_lock);  // 一次只有一个线程能通过这里
    // 含有共享数据的代码从这里开始
    for(i = 0; i < 100000; i++) {
        beers -= 1;
    }
    // ...代码结束了
    pthread_mutex_unlock(&beers_lock);

    printf("beers = %i \n", beers);
    return NULL;
}
// 另外一种上锁方式
void* drink_lots(void* a) {
    int i;
    for(i = 0; i < 100000; i++) {
        pthread_mutex_lock(&beers_lock);
        beers -= 1;
        pthread_mutex_unlock(&beers_lock);
    }
    printf("beers = %i \n", beers);
    return NULL;
}
void error(char *msg)
{
    fprintf(stderr, "%s: %s\n", msg, strerror(errno));
    exit(1);  // 非正常运行导致退出程序,这是系统级别的
}

int main()
{
    pthread_t threads[20];

    int t;
    printf("%i bottles of beer on the wall \n%i bottles of beer\n", beers, beers);
    for(t = 0; t < 20; t++) {
        if(pthread_create(&threads[t], NULL, drink_lots, NULL) == -1)
            error("fail to create thread.");
    }

    void* result;
    for(t = 0; t < 20; t++) {
        // pthread_join() 函数会等待线程结束
        if(pthread_join(threads[t], &result) == -1)
            error("fail to recycle thread."); //无法回收线程
    }
    printf("There are now %i bottles of beer on the wall\n", beers);

    return 0;
}

build:

gcc beers.c -lpthread -o beers
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在嵌入式Linux中使用多线程互斥锁可以避免多个线程同时访问共享资源而产生的竞态条件问题。下面是使用互斥锁的步骤: 1. 定义互斥锁变量 ```c pthread_mutex_t mutex; ``` 2. 初始化互斥锁 ```c pthread_mutex_init(&mutex, NULL); ``` 3. 在需要访问共享资源的代码段前加锁 ```c pthread_mutex_lock(&mutex); // 访问共享资源的代码段 pthread_mutex_unlock(&mutex); ``` 4. 在访问共享资源的代码段结束后解锁 ```c pthread_mutex_unlock(&mutex); ``` 需要注意的是,对于同一个互斥锁变量,加锁和解锁的线程必须是同一个线程,否则会导致死锁。此外,如果线程在加锁时发现锁已经被其他线程占用,则会被阻塞,直到锁被释放。 下面是一个简单的示例代码: ```c #include <pthread.h> #include <stdio.h> pthread_mutex_t mutex; int counter = 0; void* thread_function(void* arg) { int i; for (i = 0; i < 100000; i++) { pthread_mutex_lock(&mutex); counter++; pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t thread1, thread2; pthread_mutex_init(&mutex, NULL); pthread_create(&thread1, NULL, thread_function, NULL); pthread_create(&thread2, NULL, thread_function, NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); printf("counter = %d\n", counter); pthread_mutex_destroy(&mutex); return 0; } ``` 在这个示例中,两个线程分别对counter变量进行100000次加1操作,使用互斥锁保证了计数器的正确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值