linux编程---线程---互斥锁

线程间同步机制

互斥锁通信机制
互斥以排他方式防止共享数据被并发修改。
(1)在访问该资源前,首先申请该互斥锁,如果该互斥处于开锁状态,则申请到该锁对象,
并立即占有该锁,以防止其他线程访问该资源。如果该互斥锁处于锁定状态,默认阻塞等待。
(2)只有锁定该互斥锁的进程才能释放该互斥锁,其他线程的释放操作无效。

初始化锁
静态初始化互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

动态初始化互斥锁
 int pthread_mutex_init(pthread_mutex_t *restrict mutex,
              const pthread_mutexattr_t *restrict attr);
              
销毁互斥锁
 int pthread_mutex_destroy(pthread_mutex_t *mutex);
 
申请互斥锁
int pthread_mutex_lock(pthread_mutex_t *mutex);

以非阻塞方式申请互斥锁
int pthread_mutex_trylock(pthread_mutex_t *mutex);

释放互斥锁
int pthread_mutex_unlock(pthread_mutex_t *mutex);    



程序示例如下

程序共两个线程,一个线程负责从输入设备读取数据,然后存在在全局变量中,

另一个线程负责将全局变量输出到输出设备中。


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

void *tfun(void *arg);
pthread_mutex_t gmutex;

#define BUF 1024
char gdata[BUF];
int gtime = 0;

int main(int argc,char*argv[])
{
    int res;
    pthread_t th1;    
    void *thret;
    
    res = pthread_mutex_init(&gmutex,0);
    if(res != 0)
    {
        printf("mutex initialization failed\n");
        exit(-1);
    }
    res = pthread_create(&th1,0,tfun,0);
    if(res != 0)
    {
        printf("thread create failed\n");
        exit(-1);
    }
    
    pthread_mutex_lock(&gmutex);
    printf("input some text,enter 'exit' to finished\n");
    while(!gtime)
    {
        fgets(gdata,BUF,stdin);
        pthread_mutex_unlock(&gmutex);
    
        while(1)
        {
            pthread_mutex_lock(&gmutex);
            if(gdata[0] != '\0')
            {
                pthread_mutex_unlock(&gmutex);
                sleep(1);
            }
            else
                break;
        }        
    }
    pthread_mutex_unlock(&gmutex);
    printf("\n waiting for thread to finish ...\n");
    res = pthread_join(th1,&thret);
    if(res != 0)
    {
        printf("thread join failed\n");
        exit(-1);
    }
    pthread_mutex_destroy(&gmutex);
    exit(0);    
}

void *tfun(void * arg)
{
    sleep(1);
    pthread_mutex_lock(&gmutex);
    while(strncmp("end",gdata,3) != 0)    
    {
        printf("you input %d bytes %s\n",strlen(gdata)-1,gdata);
        gdata[0] = '\0';

        pthread_mutex_unlock(&gmutex);
        sleep(1);
        pthread_mutex_lock(&gmutex);
        while(gdata[0] == '\0')
        {
            pthread_mutex_unlock(&gmutex);
            sleep(1);
            pthread_mutex_lock(&gmutex);
        }
    }
    gtime = 1;
    gdata[0] = '\0';
    pthread_mutex_unlock(&gmutex);
    pthread_exit(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值