多线程并行运行,共享同一种互斥资源时,需要上互斥锁来运行,主要是用到pthread_mutex_lock函数和pthread_mutex_unlock函数对线程进行上锁和解锁

  下面是一个例子:

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

#define THREAD_NUMBER        3            /* 线程数 */
#define REPEAT_NUMBER        3            /* 每个线程的小任务数 */
#define DELAY_TIME_LEVELS 10.0         /*小任务之间的最大时间间隔*/
pthread_mutex_t mutex;

void *thrd_func(void *arg)
{
     int thrd_num = (int)arg;
     int delay_time = 0, count = 0;
     int res;
     /* 互斥锁上锁 */
     res = pthread_mutex_lock(&mutex);
     if (res)
     {
          printf("Thread %d lock failed\n", thrd_num);
          pthread_exit(NULL);
     }
     printf("Thread %d is starting\n", thrd_num);
     for (count = 0; count < REPEAT_NUMBER; count++)
     {         
     delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1;
     sleep(delay_time);
     printf("\tThread %d: job %d delay = %d\n",
                                  thrd_num, count, delay_time);
     }
     printf("Thread %d finished\n", thrd_num);
     pthread_exit(NULL);
}

int main(void)
{
     pthread_t thread[THREAD_NUMBER];
     int no = 0, res;
     void * thrd_ret;
    
     srand(time(NULL));
     /* 互斥锁初始化 */
     pthread_mutex_init(&mutex, NULL);
     for (no = 0; no < THREAD_NUMBER; no++)
     {
          res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);//创建多个线程
          if (res != 0)
          {
              printf("Create thread %d failed\n", no);
              exit(res);
          }
     }    
     printf("Create treads success\n Waiting for threads to finish...\n");
     for (no = 0; no < THREAD_NUMBER; no++)
     {
          res = pthread_join(thread[no], &thrd_ret);
          if (!res)
          {
          printf("Thread %d joined\n", no);
          }
          else
          {
              printf("Thread %d join failed\n", no);
          }
          /* 互斥锁解锁 */
          pthread_mutex_unlock(&mutex);
     }    
     pthread_mutex_destroy(&mutex);         
     return 0;       
}

一切来自对linux嵌入式的热爱

linux多线程编程之互斥锁的更多相关文章

  1. 【Linux C 多线程编程】互斥锁与条件变量

    一.互斥锁 互斥量从本质上说就是一把锁, 提供对共享资源的保护访问. 1) 初始化: 在Linux下, 线程的互斥量数据类型是pthread_mutex_t. 在使用前, 要对它进行初始化: 对于静态 ...

  2. linux c编程:互斥锁

    们常说互斥锁保护临界区,实际上是说保护临界区中被多个线程或进程共享的数据.互斥锁保证任何时刻只有一个线程在执行其中的代码. 互斥锁具有以下特点: ·原子性:把一个互斥锁定义为一个原子操作,这意味着操作 ...

  3. 笔记3 linux 多线程 条件变量+互斥锁

    //cond lock #include<stdio.h> #include<unistd.h> #include<pthread.h> struct test { ...

  4. Linux多线程编程初探

    Linux线程介绍 进程与线程 典型的UNIX/Linux进程可以看成只有一个控制线程:一个进程在同一时刻只做一件事情.有了多个控制线程后,在程序设计时可以把进程设计成在同一时刻做不止一件事,每个线程 ...

  5. ZT 为什么pthread_cond_t要和pthread_mutex_t同时使用 || pthread/Linux多线程编程

    为什么线程同步的时候pthread_cond_t要和pthread_mutex_t同时使用 (2009-10-27 11:07:23) 转载▼ 标签: 杂谈 分类: 计算机 举一个例子(http:// ...

  6. Linux多线程编程之详细分析

    线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步.互斥,这些东西将在本文中介绍.我见到这样一道面试题: 是否熟悉POSIX多线程 ...

  7. Linux多线程编程和Linux 2.6下的NPTL

    Linux多线程编程和Linux 2.6下的NPTL 在Linux 上,从内核角度而言,基本没有什么线程和进程的区别--大家都是进程.一个进程的多个线程只是多个特殊的进程他们虽然有各自的进程描述结构, ...

  8. Linux多线程编程小结

     Linux多线程编程小结 前一段时间由于开题的事情一直耽搁了我搞Linux的进度,搞的我之前学的东西都遗忘了,非常烦躁的说,如今抽个时间把之前所学的做个小节.文章内容主要总结于<Linux程序 ...

  9. Linux多线程编程阅读链接

    1. 进程与线程的一个简单解释(阮一峰) 2. linux 多线程编程 3. Linux 的多线程编程的高效开发经验 (IBM)

随机推荐

  1. iOS7适配问题

    iOS7适配问题 2013-09-28 08:32:37     我来说两句      作者:冻僵的企鹅 收藏    我要投稿 iOS 7发布了,适配问题来了,开发者都忙起来了. 先记一个iOS7 的 ...

  2. Discuz!提取文章标签

    <?php    //强制使用字符集 @header('Content-Type: text/html; charset=gbk');    $subjectenc ='title'; //这是 ...

  3. uniq详解

    一.简介 报告或删除文件中重复的行. uniq 命令读取由 InFile 参数指定的标准输入或文件.该命令首先比较相邻的行,然后除去第二行和该行的后续副本.重复的行一定相邻.(在发出 uniq 命令之 ...

  4. 【转】vsftp 遇到错误 500 OOPS: vsftpd: refusing to run with writable root inside chroot()--不错

    原文网址:http://linux.it.net.cn/e/server/ftp/2015/0227/13554.html 当我们限定了用户不能跳出其主目录之后,使用该用户登录FTP时往往会遇到这个错 ...

  5. Windows搭建SMTP邮件服务器

    From:http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/e4cf06f5-9a36-474b-b ...

  6. apacheOfbiz

    一.ofbiz 用自身数据库安装 1. 由 binary 安装: 由 binary 安装非常简单, 以下是安装方法: 下载ofbiz-2.0-beta1-complete.tar.gz, 注意不是of ...

  7. Linux shell编程02 shell程序的执行 及文件权限

    第一个shell脚本 1.       shell编程的方式 交互式shell编程 非交互式shell编程:执行的语句存放到一个文件 shell脚本:可以任意文件名,建议扩展名为sh 2.       ...

  8. ps&&/proc/pid/xxx

    ps 如果想看一个进程的启动时间,可以用lstart来看 [root@jiangyi02.sqa.zmf /home/ahao.mah] #ps -eo pid,lstart,etime,cmd |g ...

  9. Test注解的两个属性:expected和timeout

    JUnit4:Test文档中的解释: The Test annotation supports two optional parameters. The first, expected, declar ...

  10. Ant-进阶

    Ant的概念 可能有些读者并不连接什么是Ant以及入可使用它,但只要使用通过Linux系统得读者,应该知道make这个命令.当编译Linux内核及一些软件的源程序时,经常要用这个命令.Make命令其实 ...