一个简单的互斥量的例子

1。 互斥量
    Linux提供了控制线程执行和访问代码临界区域的方法。其中最基本的两种办法是信号量和互斥量。
关于信号量,笔者在 Linux信号量介绍中介绍

    本文只介绍semaphore.h 相关的信号量的简单的操作。关于信号量在笔者其他博客里有详细介绍。

    Linux还有其他共享内存的方法。

2. 与互斥量相关的函数


    # include <pthread.h >

     int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *mutexattr); //创建互斥量

     int pthread_mutex_lock(pthread_mutex_t *mutex); //加锁

     int pthread_mutex_unlock(pthread_mutex_t *mutex); //解锁

     int pthread_mutex_destroy(pthread_mutex_t *mutex); //清理互斥量

3. 一个简单的程序例子

 

 


   
/***************************************
 *    @file            mutex.c
 *    @brief        互斥锁
 *    @author        Windeal
 *    @date        2013/08/06
***************************************/

 
# include <stdlib.h >
# include <stdio.h >
# include <unistd.h >
# include <string.h >
# include <pthread.h >
 
# define WORK_SIZE 1024
char work_area[WORK_SIZE];
 
pthread_mutex_t work_mutex;
 
int time_to_exit = 0;
 
void *thread_function( void *arg);
 
int main( int argc, char * argv[])
{
     int ret;
    pthread_t a_thread;
     void *thread_result;
 
    ret = pthread_mutex_init( &work_mutex, NULL);
     if (ret != 0) {
        perror( "pthread_mutex_init failed\n");
        exit(EXIT_FAILURE);
    }
 
 
 
    printf( "It time to create a thread!\n");    /
    ret = pthread_create( &a_thread, NULL, thread_function, NULL);
     if (ret != 0) {
        perror( "Thread creation failed!\n");
        exit(EXIT_FAILURE);
    }
 
    pthread_mutex_lock( &work_mutex);     //加锁
    printf( "Input some text. Enter \"end\" to finished\n");
     while ( !time_to_exit) {         //
        fgets(work_area, WORK_SIZE, stdin);
        pthread_mutex_unlock( &work_mutex); // 解锁
         while ( 1) {
            pthread_mutex_lock( &work_mutex);     //加锁
             if (work_area[ 0] != '\0'){         //如果有数据则到解锁,没有数据则继续输入
                pthread_mutex_unlock( &work_mutex); // 解锁 因为workarea里有数据
                                     //因此到另一个线程里比对
                sleep( 1);
            }
             else {
                 break;
            }
        }
    }
 
    pthread_mutex_unlock( &work_mutex); // 解锁
    printf( "Waiting for thread finish!\n"); /
    ret = pthread_join(a_thread, &thread_result);
     if (ret != 0) {
        perror( "Thread finished failed\n");
        exit(EXIT_FAILURE);
    }
 
    printf( "Thread joined\n");
    pthread_mutex_destroy( &work_mutex);
    exit(EXIT_SUCCESS);
 
}
 
void *thread_function( void * arg) {
    sleep( 1);
    pthread_mutex_lock( &work_mutex);
     while (strncmp( "end", work_area, 3) != 0) {
        printf( "You have enter %d charactor\n", strlen(work_area) - 1);
        work_area[ 0] = '\0';     //清零数据区
        pthread_mutex_unlock( &work_mutex);      //让主线程继续输入数据
        sleep( 1);
        pthread_mutex_lock( &work_mutex);   //尝试加锁,如果主线程已输入数据,则加锁成功
         while (work_area[ 0] == '\0') {     //如果输入为空,则继续等待输入.输入不为空时,跳出循环
            pthread_mutex_unlock( &work_mutex);
            sleep( 1);
            pthread_mutex_lock( &work_mutex);
        }
    }
 
    time_to_exit = 1;
    work_area[ 0] = '\0';
    pthread_mutex_unlock( &work_mutex);
    pthread_exit( 0);
 
}
 

结果如下所示:

 

 

 

 

 

 

 

 

 

 

 

 

    

转载于:https://www.cnblogs.com/Windeal/p/4284677.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在多线程编程中,为了防止多个线程同时访问共享资源而导致的数据竞争问题,需要使用同步机制来实现线程间的协调和互斥。而互斥是一种常用的同步机制,在多线程编程中被广泛使用互斥是一种线程同步原语,用于保护共享资源。当一个线程需要访问共享资源时,它需要先获取该资源的互斥。如果该互斥已经被其他线程占用,则当前线程会被阻塞,直到该互斥被释放。一旦该互斥被释放,当前线程就可以获取该互斥,访问共享资源,并将该互斥加锁。当该线程完成对共享资源的访问后,它需要将该互斥解锁,以便其他线程可以获取该互斥继续访问共享资源。 互斥使用一般涉及到以下四个函数: 1. pthread_mutex_init():初始化互斥; 2. pthread_mutex_lock():加锁互斥; 3. pthread_mutex_unlock():解锁互斥; 4. pthread_mutex_destroy():销毁互斥。 下面是一个简单例子,展示了如何使用互斥实现线程同步: ``` #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex; // 定义互斥 void *thread_func(void *arg) { pthread_mutex_lock(&mutex); // 加锁互斥 printf("Thread %ld is running.\n", pthread_self()); pthread_mutex_unlock(&mutex); // 解锁互斥 pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t t1, t2; pthread_mutex_init(&mutex, NULL); // 初始化互斥 pthread_create(&t1, NULL, thread_func, NULL); pthread_create(&t2, NULL, thread_func, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_mutex_destroy(&mutex); // 销毁互斥 return 0; } ``` 在上面的例子中,我们定义了一个互斥 mutex,然后在线程函数中分别加锁和解锁该互斥。在主函数中,我们创建了两个线程,并等待它们执行完毕后退出程序。需要注意的是,我们必须在程序退出之前销毁该互斥,以免产生内存泄漏。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值