线程之互斥锁

27 篇文章 0 订阅
24 篇文章 0 订阅

在多线程中对共享资源的访问

在一个多线程的程序中,有时需要同时对共享资源的访问,就会造成对共享资源的读写问题。
例如:有五个线程,其中一个对共享资源进行修改,其余四个线程需要同时对共享资源进行读访问。势必会造成其余四个线程读取数据的不稳定。此时就可以使用互斥锁去解决这一问题。
当修改共享资源的线程需要对数据进行修改时,首先得到互斥锁,进行加锁。其他进程就被阻塞不可以去读取资源了。操作完成后,解锁,其他线程就可以对资源进行访问了。
关于互斥锁的操作有以下步骤:

1、初始化互斥锁

pthread_mutex_init(&mutex,NULL);

2、对操作的数据加锁

pthread_mutex_lock(&mutex); “`

3、对操作的数据解锁

pthread_mutex_unlock(&mutex);

4、销毁互斥锁

pthread_mutex__destroy(&mutex); “

`

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

//目的创建多个线程,一个对共享资源进行修改,四个对共享资源进行访问

#if 0
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
int pthread_join(pthread_t thread, void **retval);
#endif

char name[] = "hello,world!";
pthread_mutex_t mutex;

void *start_routine_read(void *arg)
{

    while(1)
    {
        pthread_mutex_lock(&mutex);
        printf("@%d,%s\n",pthread_self(),name);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return (void *)0;
}

void *start_routine_write(void *arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        char temp_str[12] = "";
        printf("input string:");
        scanf("%s",temp_str);
        strcpy(name,temp_str);
        printf("@%d,write data:%s\n",pthread_self(),name);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return (void *)0;   
}
int main(void)
{
    pthread_t thread[5];
    int i = 0;

    pthread_mutex_init(&mutex,NULL);
    //创建5个线程
    for(i = 1;i < 5;i++)
    {
        pthread_create(thread+i,NULL,start_routine_read,NULL);
    }
    pthread_create(thread,NULL,start_routine_write,NULL);

    while(1);
    pthread_mutex_destroy(&mutex);
    //回收线程资源
    for(i = 1;i < 5;i++)
    {
        pthread_join(thread[i],NULL);
    }
    pthread_join(thread[0],NULL);
    return 0;
}

代码中尚有不完善指出,请指出,谢谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值