pthread_mutex_lock线程锁使用简单示例

本文通过一个简单的示例介绍了pthread_mutex_lock线程锁的使用,演示了在多线程环境下如何保证数据的一致性。在加锁的情况下,两个线程交替修改整数,确保线程安全。当移除锁后,通过验证输出,可以观察到数据竞争的现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#define __USE_LARGEFILE64
#define _LARGEFILE64_SOURCE
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <pthread.h>
#define mutex_lock


pthread_mutex_t mutex;
void *thread_function_even(void *inpara)
{
    int *num = (int *)inpara;
    long unsigned int thread_num = pthread_self();
    pthread_detach( thread_num ); /*detach to be an independent thread*/
    while(1)
    {
#ifdef mutex_lock
        pthread_mutex_lock(&mutex);
#endif
        *num = (*num * 2)% 100;
        usleep(1);
        printf("int thread_function_even,num:%d,is even:%d\n",*num, (0 == *num % 2) );
#ifdef mutex_lock
        pthread_mutex_unlock(&mutex);
#endif
    }
}
void *thread_function_odd(void *inpara)
{
    int *num = (int *)inpara;
    long unsigned int thread_num = pthread_self();
    pthread_detach( thread_num ); /*detach to be an independent thread*/
    while(1)
    {
#ifdef mutex_lock
        pthread_mutex_lock(&mutex);
#endif
        *num = (*num * 2)% 100 + 1;
        usleep(1);
        printf("int thread_function_odd,num:%d,is even:%d\n",*num, (0 == *num % 2) );
#ifdef mutex_lock
        pthread_mutex_unlock(&mutex);
#endif
    }
}
int main (int argc, char *argv[])
{
    /*mutex is a lock,everyone only can operate an array by get the mutex*/
#ifdef mutex_lock
    pthread_mutex_init(&mutex, NULL);
#endif


    /*create two threads,one change the num to even,the other change the num to odd*/
    int i = 0;
    pthread_t thread_even,thread_odd;
    pthread_create(&thread_even, NULL, thread_function_even, &i);
    pthread_create(&thread_odd, NULL, thread_function_odd, &i);


    while(1);
#ifdef mutex_lock
    pthread_mutex_destroy(&mutex);
#endif

}

1.编译:gcc main.c -lpthread -g

2.运行:./a > 1 十几秒后ctrl c停掉

3.验证锁是否有效,以下两条命令都搜不到结果:

cat 1|grep thread_function_odd|grep "even:1"
cat 1|grep thread_function_even|grep "even:0"

4.去掉代码中的锁:注释#define mutex_lock

5.去掉后验证不加锁后是否正确,步骤3中的两条命令能搜到结果

cat 1|grep thread_function_odd|grep "even:1"
cat 1|grep thread_function_even|grep "even:0"

6.代码的原理:创建两个线程,两个线程都操作同一个整数,一个只把整数变为偶数,一个只把整数变为奇数,加锁的情况下,偶数线程中打印的数字全为偶数,奇数线程中打印的数字全为奇数

`pthread_mutex_lock()`函数是POSIX线程库(pthread)中用于锁定互斥锁(mutex)的一个关键操作,它在线程环境中确保在同一时刻只有一个线程可以访问共享资源。以下是它的一个基本使用示例: ```c #include <pthread.h> // 引入线程库 // 定义全局互斥锁变量 pthread_mutex_t mutex; // 初始化互斥锁 int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr) { if (pthread_mutex_init(&mutex, NULL) != 0) { perror("Mutex initialization failed"); return 1; } return 0; } // 示例函数,需要获取锁才能执行 void thread_function(void* arg) { pthread_mutex_lock(&mutex); // 尝试获取锁 if (pthread_mutex_trylock(&mutex) == EBUSY) { // 如果已锁,等待 printf("Waiting for the lock...\n"); pthread_mutex_lock(&mutex); } // 现在锁已被获取,可以在临界区更新共享数据 // ... pthread_mutex_unlock(&mutex); // 释放锁 } int main() { pthread_t my_thread; // 创建一个新的线程 // 创建并初始化线程 if (pthread_create(&my_thread, NULL, thread_function, NULL) != 0) { perror("Thread creation failed"); return 1; } // 等待线程结束 pthread_join(my_thread, NULL); // 销毁互斥锁 pthread_mutex_destroy(&mutex); return 0; } ``` 在这个例子中,如果主线程试图解锁一个已经被其他线程持有的锁,`pthread_mutex_lock()`会阻塞,直到锁被释放。当线程完成对资源的操作后,应该使用`pthread_mutex_unlock()`来释放锁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值