互斥锁演示函数

此代码示例展示了如何在C语言中使用pthread库实现多线程,并通过互斥锁(pthread_mutex_t)保护临界资源。程序创建两个线程,一个用于循环打印字符串,另一个用于循环倒置字符串。互斥锁确保了对共享资源的同步访问,防止数据竞争。
摘要由CSDN通过智能技术生成

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

char str[]="1234567";
//临界资源(共享资源)
pthread_mutex_t mutex;//互斥锁

void *callBack1(void *arg)
{
    while(1){
    /****临界区***/
        pthread_mutex_lock(&mutex);//上锁
        printf("%s\n",str);
    pthread_mutex_unlock(&mutex);//解锁
    /****临界区***/
    }
}
void *callBack2(void *arg)
{
    int i=0;
    char temp=0;
    while(1){
    /****临界区***/                                                                                                                                                                                                                                                                                                                                                                                                                               
        pthread_mutex_lock(&mutex);//上锁
        for(i=0;i<strlen(str)/2;i++)
        {
            temp=str[i];
            str[i]=str[strlen(str)-1-i];
            str[strlen(str)-1-i]=temp;
        }
    pthread_mutex_unlock(&mutex);//解锁
    /****临界区***/
    }
}
int main(int argc, const char *argv[])
{
    //创建互斥锁
    if(pthread_mutex_init(&mutex,NULL)!=0)
    {
        perror("pthread_mutex_init");
        return -1;
    }
    printf("mutex_init success\n");
    pthread_t tid1,tid2;
    //创建线程,循环打印
    if(pthread_create(&tid1,NULL,callBack1,NULL)!=0)
    {
    perror("pthread_mutex_create");
    return -1;
    }
    //创建线程,循环倒置
    if(pthread_create(&tid2,NULL,callBack1,NULL)!=0)
    {
    perror("pthread_mutex_create");
    return -1;
    }
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    //销毁互斥锁
    pthread_mutex_destroy(&mutex);

    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值