分Cas和Block模式实现了demo, 供入门学习使用,代码全部是远程实现。

直接上代码:

  1. /*
  2. ============================================================================
  3. Name : Producer.c
  4. Author : qionghui.fang
  5. Version : 1.0
  6. Date : 2019年6月11日 下午2:32:30
  7. Copyright : Your copyright notice
  8. Description : Main
  9. ============================================================================
  10. */
  11.  
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <pthread.h>
  15. #include <semaphore.h>
  16. #include <unistd.h>
  17.  
  18. #include "header.h"
  19.  
  20. int main(void) {
  21.  
  22. printf("Start...\n");
  23.  
  24. // 在阻塞模式下初始化信号量
  25. if(TC > ){
  26. pthread_mutex_init(&mutex_add,NULL);
  27. pthread_mutex_init(&mutex_take,NULL);
  28. }
  29.  
  30. printf("Producer1 Thread init ...\n");
  31. pthread_t producer1;
  32. ThreadParam p1Params = {"Producer1", &mutex_add};
  33. pthread_create(&producer1, NULL, (void *)addBean, &p1Params);
  34.  
  35. printf("Producer2 Thread init ...\n");
  36. pthread_t producer2;
  37. ThreadParam p2Params = { "Producer2", &mutex_add};
  38. pthread_create(&producer2, NULL, (void *)addBean, &p2Params);
  39.  
  40. printf("Consumer1 Thread init ...\n");
  41. pthread_t consumer1;
  42. ThreadParam c1Params = { "Consumer1", &mutex_take};
  43. pthread_create(&consumer1, NULL, (void *)takeBean, &c1Params);
  44.  
  45. printf("Consumer2 Thread init ...\n");
  46. pthread_t consumer2;
  47. ThreadParam c2Params = { "Consumer2", &mutex_take};
  48. pthread_create(&consumer2, NULL, (void *)takeBean, &c2Params);
  49.  
  50. printf("Consumer3 Thread init ...\n");
  51. pthread_t consumer3;
  52. ThreadParam c3Params = { "Consumer3", &mutex_take};
  53. pthread_create(&consumer3, NULL, (void *)takeBean, &c3Params);
  54.  
  55. pthread_join(producer1, NULL);
  56. printf("\n\nhere 1");
  57. pthread_join(producer2, NULL);
  58. printf("\nhere2");
  59. pthread_join(consumer1, NULL);
  60. pthread_join(consumer2, NULL);
  61. pthread_join(consumer3, NULL);
  62. printf("\n\nhere3");
  63.  
  64. printf("\nEnd.");
  65.  
  66. return EXIT_SUCCESS;
  67. }
  1. /*
  2. * header.h
  3. *
  4. * Created on: 2019年6月11日
  5. * Author: fangdahui
  6. */
  7.  
  8. #include <pthread.h>
  9. #include <semaphore.h>
  10.  
  11. #ifndef HEADER_H_
  12. #define HEADER_H_
  13.  
  14. typedef int boolean;
  15. #define TRUE 1
  16. #define FALSE 0
  17.  
  18. // 队列数量 BeanCount
  19. #define BC 10
  20. // thread count: <=3 为CAS模式 大于3为阻塞模式
  21. #define TC 3
  22.  
  23. typedef struct bean{
  24. int no;
  25. char* msg;
  26. }Bean_t;
  27.  
  28. typedef struct threadParam{
  29. char* threadName;
  30. pthread_mutex_t* mutex;
  31. }ThreadParam;
  32.  
  33. // 队列
  34. Bean_t beanList[];
  35. volatile int beanListSize;
  36.  
  37. // 原子操作 cmpxchg
  38. boolean cmpxchg(volatile int* dest, int compareValue, int newValue);
  39.  
  40. // 加入元素
  41. void *addBean(ThreadParam* params);
  42. // 互斥信号
  43. pthread_mutex_t mutex_add;
  44.  
  45. // 获取元素
  46. void *takeBean(ThreadParam* params);
  47. // 互斥信号
  48. pthread_mutex_t mutex_take;
  49.  
  50. #endif /* HEADER_H_ */
  1. /*
  2. ============================================================================
  3. Name : Atom.c
  4. Author : qionghui.fang
  5. Version : 1.0
  6. Date : 2019年6月12日 上午8:53:35
  7. Copyright : Your copyright notice
  8. Description : CAS原子实现
  9. ============================================================================
  10. */
  11.  
  12. #include "header.h"
  13.  
  14. // Adding a lock prefix to an instruction on MP machine
  15. #define LOCK_IF_MP(mp) "cmp $0, " #mp "; je 1f; lock; 1: "
  16.  
  17. boolean cmpxchg(volatile int* dest, int compareValue, int newValue){
  18.  
  19. // 暂存旧值
  20. int oldValue = *dest;
  21.  
  22. // 默认多核
  23. boolean mp = TRUE;
  24.  
  25. // 调用 cmpxchgl 指令
  26. __asm__ volatile (LOCK_IF_MP(%) "cmpxchgl %1,(%3)"
  27. : "=a" (newValue)
  28. : "r" (newValue), "a" (compareValue), "r" (dest), "r" (mp)
  29. : "cc", "memory");
  30.  
  31. // 调用结束后 若地址目标值发生变更,则说明替换成功
  32. if(*dest != oldValue){
  33. return TRUE;
  34. }
  35.  
  36. // 其它为失败
  37. return FALSE;
  38. }
  1. /*
  2. ============================================================================
  3. Name : Producer.c
  4. Author : qionghui.fang
  5. Version : 1.0
  6. Date : 2019年6月11日 下午2:32:30
  7. Copyright : Your copyright notice
  8. Description : 生产者
  9. ============================================================================
  10. */
  11.  
  12. #include "header.h"
  13. #include <stdio.h>
  14. #include <unistd.h>
  15. #include <semaphore.h>
  16.  
  17. void *addBean(ThreadParam * params){
  18.  
  19. while(TRUE){
  20.  
  21. // 生产1次 休眠1秒
  22. sleep();
  23.  
  24. // 走CAS模式
  25. if(TC <= ){
  26. int oldSize = beanListSize;
  27. int newSize = oldSize + ;
  28.  
  29. if(newSize >= BC){
  30. printf("\n[CasMode]%s: 队列已达最大长度,本次不加入,当前长度为:%d", params->threadName, beanListSize);
  31. sleep();
  32. //continue;
  33. break;
  34. }
  35.  
  36. if(cmpxchg(&beanListSize, oldSize, newSize)){
  37. // 队列长度+1
  38. beanListSize = newSize;
  39. Bean_t bean = {beanListSize, "beanListSize"};
  40. beanList[beanListSize] = bean;
  41.  
  42. printf("\n[CasMode]%s: CAS成功,当前长度为:%d", params->threadName, beanListSize);
  43. }
  44. else{
  45. printf("\n[CasMode]%s: CAS失败,进行下一轮尝试,当前长度为:%d", params->threadName, beanListSize);
  46. }
  47. }
  48.  
  49. else{
  50. // 加锁
  51. pthread_mutex_lock(params->mutex);
  52.  
  53. beanListSize ++;
  54.  
  55. if(beanListSize >= ){
  56. printf("\n[BlockMode]%s: 队列已达最大长度,本次不加入,当前长度为:%d", params->threadName, beanListSize);
  57. sleep();
  58. //continue;
  59. //释放锁
  60. pthread_mutex_unlock(params->mutex);
  61. break;
  62. }
  63.  
  64. Bean_t bean = {beanListSize, "beanListSize"};
  65. beanList[beanListSize] = bean;
  66.  
  67. printf("\n[BlockMode]%s: 加锁成功,添加元素,当前长度为:%d", params->threadName, beanListSize);
  68.  
  69. //释放锁
  70. pthread_mutex_unlock(params->mutex);
  71. }
  72. }
  73.  
  74. printf("\n%s: 线程终止,当前长度为:%d\n", params->threadName, beanListSize);
  75. return ;
  76. }
  1. /*
  2. ============================================================================
  3. Name : Consumer.c
  4. Author : qionghui.fang
  5. Version : 1.0
  6. Date : 2019年6月21日 上午9:56:30
  7. Copyright : Your copyright notice
  8. Description : 消费者
  9. ============================================================================
  10. */
  11.  
  12. #include "header.h"
  13. #include <stdio.h>
  14. #include <unistd.h>
  15. #include <semaphore.h>
  16.  
  17. void *takeBean(ThreadParam* params){
  18.  
  19. sleep();
  20.  
  21. while(TRUE){
  22. // 消费一次 休眠2秒
  23. sleep();
  24.  
  25. // 走CAS模式
  26. if(TC <= ){
  27.  
  28. int oldSize = beanListSize;
  29. int newSize = oldSize - ;
  30.  
  31. if(newSize < ){
  32. printf("\n[CasMode]%s: 消息已消费完,本次不能消费,当前长度为:%d", params->threadName, beanListSize);
  33. //continue;
  34. break;
  35. }
  36.  
  37. if(cmpxchg(&beanListSize, oldSize, newSize)){
  38. // 队列长度-1
  39. beanListSize = newSize;
  40. printf("\n[CasMode]__%s: CAS成功,当前长度为:%d",params->threadName, beanListSize);
  41.  
  42. int i;
  43. for(i=; i<BC;i++){
  44. Bean_t *bean = &beanList[i];
  45. if(bean->no != ){
  46. bean->no = ;
  47. bean->msg = NULL;
  48. break;
  49. }
  50. }
  51. }
  52. else{
  53. printf("\n[CasMode]%s:CAS失败,进行下一轮尝试,当前长度为:%d", params->threadName, beanListSize);
  54. }
  55. }
  56. else{
  57. // 加锁
  58. pthread_mutex_lock(params->mutex);
  59.  
  60. beanListSize --;
  61.  
  62. if(beanListSize < ){
  63. printf("\n[BlockMode]__%s: 消息已消费完,本次不能消费,当前长度为:%d", params->threadName, beanListSize);
  64. sleep();
  65. //continue;
  66. //释放锁
  67. pthread_mutex_unlock(params->mutex);
  68. break;
  69. }
  70.  
  71. int i;
  72. for(i=; i<;i++){
  73. Bean_t *bean = &beanList[i];
  74. if(bean->no != ){
  75. bean->no = ;
  76. bean->msg = NULL;
  77. break;
  78. }
  79. }
  80.  
  81. printf("\n[BlockMode]__%s: 加锁成功, 消费元素,当前长度为:%d", params->threadName, beanListSize);
  82.  
  83. //释放锁
  84. pthread_mutex_unlock(params->mutex);
  85. }
  86. }
  87.  
  88. printf("\n%s: 线程终止,当前长度为:%d\n", params->threadName, beanListSize);
  89. return ;
  90. }

运行结果:

CAS模式:

阻塞Block模式(头文件里TC改为3以上,如5):

逐行写的代码,收获不小。

这个适用于初学者,还是要在本地跑一跑。

祝好运。

【原创实现】C 多线程入门Demo CAS Block 2种模式实现的更多相关文章

  1. SQL Server复制入门(二)----复制的几种模式

    简介 本系列文章的上一篇对复制是什么做了一个概述.本篇文章根据发布服务器,分发服务器和订阅服务器的组织方式和复制类型来讲述常用复制的几种模式. 模式的选择 选择复制的模式取决于多个方面.首先需要考虑具 ...

  2. SQL Server复制入门(二)----复制的几种模式 (转载)

    简介本系列文章的上一篇对复制是什么做了一个概述.本篇文章根据发布服务器,分发服务器和订阅服务器的组织方式和复制类型来讲述常用复制的几种模式. 模式的选择选择复制的模式取决于多个方面.首先需要考虑具体的 ...

  3. 2.1多线程(java学习笔记) java中多线程的实现(附静态代理模式)

    一.多线程 首先我们要清楚程序.进程.线程的关系. 首先进程从属于程序,线程从属于进程. 程序指计算机执行操作或任务的指令集合,是一个静态的概念. 但我们实际运行程序时,并发程序因为相互制约,具有“执 ...

  4. Java多线程学习(一)Java多线程入门

    转载请备注地址:https://blog.csdn.net/qq_34337272/article/details/79640870 系列文章传送门: Java多线程学习(一)Java多线程入门 Ja ...

  5. JAVA实现多线程入门

    package com.thread;/** * 1:程序员可以在程序中执行多个线程,每一个线程完成一个功能,并于其他线程并发执行,这种 * 机制被称为多线程 * 2:实现线程的两种方法是,分别是继承 ...

  6. 【SSH系列】初识spring+入门demo

    学习过了hibernate,也就是冬天,经过一个冬天的冬眠,当春风吹绿大地,万物复苏,我们迎来了spring,在前面的一系列博文中,小编介绍hibernate的相关知识,接下来的博文中,小编将继续介绍 ...

  7. 基于springboot构建dubbo的入门demo

    之前记录了构建dubbo入门demo所需的环境以及基于普通maven项目构建dubbo的入门案例,今天记录在这些的基础上基于springboot来构建dubbo的入门demo:众所周知,springb ...

  8. apollo入门demo实战(二)

    1. apollo入门demo实战(二) 1.1. 下载demo 从下列地址下载官方脚本和官方代码 https://github.com/nobodyiam/apollo-build-scripts ...

  9. lua入门demo(HelloWorld+redis读取)

    1. lua入门demo 1.1. 入门之Hello World!! 由于我习惯用docker安装各种软件,这次的lua脚本也是运行在docker容器上 openresty是nginx+lua的各种模 ...

随机推荐

  1. python 元类 MetaClass

    type() 动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的. 比方说我们要定义一个Hello的class,就写一个hello.py模块: class Hel ...

  2. 【微信小程序】图片压缩-纯质量压缩,非长宽裁剪压缩

      原理:利用canvas来实现,将图片绘制到canvas上,然后canvas转图片时,微信提供的一个方法wx.canvasToTempFilePath(Object object, Object t ...

  3. Spring Boot任务(定时,异步,邮件)

    一.定时任务 开启定时任务(在Spring Boot项目主程序上添加如下注解) @EnableScheduling //开启定时任务的注解 创建定时任务(创建一个Service如下) @Service ...

  4. AIX中文件系统管理

    1.文件系统类型 AIX主要支持的文件系统有: JFS(Journaled  File  Systems)   日志型文件系统     JFS2(Enhanced  Journaled  File S ...

  5. Git 查看远端仓库地址

    git remote -v

  6. yum 安装mysql-server 5.6

    # rpm ivh http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm # yum install -y mysql-s ...

  7. tensorflow中张量_常量_变量_占位符

    1.tensor 在tensorflow中,数据是被封装在tensor对象中的.tensor是张量的意思,即包含从0到任意维度的张量.常数是0维度的张量,向量是1维度的张量,矩阵是二维度的张量,以及还 ...

  8. @ResponseBody 注解是什么意思?

    1. @ResponseBody注解的作用是将Controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据 ...

  9. Mac 升级python2.7 到 3.5

      Mac 系统 OSX 10.12 以上 第1步:下载Python3.5 下载地址如下: Python3.5 第二步:安装python 3.50 点击下载好的pkg文件进行安装,安装完成之后,pyt ...

  10. Puppet利用Nginx多端口实现负载均衡

    随着公司应用需求的增加,需要不断的扩展,服务器数量也随之增加,当服务器数量不断增加,我们会发现一台puppetmaster压力大,解析缓慢,而且时不时出现"time out"之类的 ...