C语言多线程互斥锁

互斥锁是为了防止多个线程同时操作临界资源,下面看看用法:

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

pthread_mutex_t mute;
int value = 0;
void *fun(void *arg){
    //上锁,函数是阻塞的
    pthread_mutex_lock(&mute);
    printf("now is %d and old value is %d \n",*((int *)arg), value);
    ++value;
    printf("now is %d and new value is %d \n",*((int *)arg), value);
    //解锁
    pthread_mutex_unlock(&mute);
}
int main(){

    pthread_t threads[5];
    int thread_id[5];
    //创建锁,相当于new一个对象
    pthread_mutex_init(&mute, NULL);
    for(int i=0; i<5; ++i){
        thread_id[i] = i;
        pthread_create(&threads[i], NULL, fun, (void *)&thread_id[i]);
    }
    for(int i=0; i<5; ++i)
        int rc = pthread_join(threads[i], NULL);
    //释放互斥锁
    pthread_mutex_destroy(&mute);
    return 0;
}

运行结果:

可以看出线程的运行顺序是不确定的,一个线程对资源上锁了,其他线程想上锁只能被阻塞。加入去掉互斥锁的结果如下:

可以看出同一个线程内操作value的前后值是异常的。

C语言中,线程互斥锁是一种同步机制,用于协调多个线程之间的访问共享资源。在多线程程序中,如果多个线程同时访问同一个共享资源,会导致数据竞争和不确定性结果。为了避免这种情况,我们需要使用互斥锁来确保在任何给定时刻只有一个线程可以访问共享资源。 以下是使用C语言线程互斥锁的基本步骤: 1.包含头文件:需要包含头文件< pthread.h>,该头文件中包含了互斥锁相关的函数定义。 2.定义互斥锁:使用 pthread_mutex_t 数据类型定义互斥锁。 3.初始化互斥锁:使用 pthread_mutex_init() 函数初始化互斥锁。 4.加锁:使用 pthread_mutex_lock() 函数加锁,确保只有一个线程可以访问临界区。 5.解锁:使用 pthread_mutex_unlock() 函数解锁,允许其他线程访问临界区。 6.销毁互斥锁:使用 pthread_mutex_destroy() 函数销毁互斥锁。 下面是一个简单的示例程序,展示了如何使用互斥锁来保护共享变量: ```c #include <pthread.h> #include <stdio.h> pthread_mutex_t mutex; int count = 0; void* increment(void* arg) { int i; for (i = 0; i < 10000; i++) { pthread_mutex_lock(&mutex); count++; pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t thread1, thread2; // 初始化互斥锁 pthread_mutex_init(&mutex, NULL); // 创建线程 pthread_create(&thread1, NULL, increment, NULL); pthread_create(&thread2, NULL, increment, NULL); // 等待线程结束 pthread_join(thread1, NULL); pthread_join(thread2, NULL); // 销毁互斥锁 pthread_mutex_destroy(&mutex); printf("Count: %d\n", count); return 0; } ``` 在上面的示例程序中,我们定义了一个名为 count 的共享变量,并创建了两个线程来对其进行加法操作。在每个线程的循环中,我们使用 pthread_mutex_lock() 函数来锁定互斥锁,以确保每个线程都可以独立访问临界区。在 count 变量更新后,我们使用 pthread_mutex_unlock() 函数来解锁互斥锁,允许其他线程访问临界区。最后,我们使用 pthread_mutex_destroy() 函数销毁互斥锁,并输出最终的 count 值。 通过使用互斥锁,我们可以确保多个线程之间的共享资源访问是安全和有序的。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值