#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <stdint.h>
#include <pthread.h>
typedef struct
{
int * array_num;
int count;
bool is_front;
} thread_arg;
#define NUM_COUNT 1000000
#define RANDOM_NUM_MIN 0
#define RANDOM_NUM_MAX 9
uint64_t sum = 0;
uint64_t sum_with_mutex = 0;
uint64_t sum_with_mutex_and_local = 0;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx_with_local = PTHREAD_MUTEX_INITIALIZER;
void get_random_num(int * array_num, int count)
{
srand(time(NULL));
for(int i = 0; i < count; i++)
{
array_num[i] = rand() % (RANDOM_NUM_MAX - RANDOM_NUM_MIN + 1) + RANDOM_NUM_MIN;
}
}
void * thread_function(void * arg)
{
int * array_num = (*(thread_arg *)arg).array_num;
int count = (*(thread_arg *)arg).count;
bool is_front = (*(thread_arg *)arg).is_front;
int start_index = is_front ? 0 : count / 2;
int end_index = is_front ? count / 2 : count;
double center_num = (double)(RANDOM_NUM_MAX + RANDOM_NUM_MIN) / 2;
for(int i = start_index; i < end_index; i++)
{
if(array_num[i] > center_num)
{
sum += array_num[i];
}
}
return NULL;
}
void * thread_function_with_mutex(void * arg)
{
int * array_num = (*(thread_arg *)arg).array_num;
int count = (*(thread_arg *)arg).count;
bool is_front = (*(thread_arg *)arg).is_front;
int start_index = is_front ? 0 : count / 2;
int end_index = is_front ? count / 2 : count;
double center_num = (double)(RANDOM_NUM_MAX + RANDOM_NUM_MIN) / 2;
for(int i = start_index; i < end_index; i++)
{
if(array_num[i] > center_num)
{
if(pthread_mutex_lock(&mtx) != 0)
{
perror("pthread_mutex_lock");
exit(EXIT_FAILURE);
}
sum_with_mutex += array_num[i];
if(pthread_mutex_unlock(&mtx) != 0)
{
perror("pthread_mutex_unlock");
exit(EXIT_FAILURE);
}
}
}
return NULL;
}
void * thread_function_with_mutex_and_local(void * arg)
{
int sum = 0;
int * array_num = (*(thread_arg *)arg).array_num;
int count = (*(thread_arg *)arg).count;
bool is_front = (*(thread_arg *)arg).is_front;
int start_index = is_front ? 0 : count / 2;
int end_index = is_front ? count / 2 : count;
double center_num = (double)(RANDOM_NUM_MAX + RANDOM_NUM_MIN) / 2;
for(int i = start_index; i < end_index; i++)
{
if(array_num[i] > center_num)
{
sum += array_num[i];
}
}
if(pthread_mutex_lock(&mtx_with_local) != 0)
{
perror("pthread_mutex_lock");
exit(EXIT_FAILURE);
}
sum_with_mutex_and_local += sum;
if(pthread_mutex_unlock(&mtx_with_local) != 0)
{
perror("pthread_mutex_unlock");
exit(EXIT_FAILURE);
}
return NULL;
}
uint64_t calculate_sum(int * array_num, int count)
{
uint64_t sum = 0;
double center_num = (double)(RANDOM_NUM_MAX + RANDOM_NUM_MIN) / 2;
for(int i = 0; i < count; i++)
{
if(array_num[i] > center_num)
{
sum += array_num[i];
}
}
return sum;
}
void print_array_num(int * array_num, int count)
{
printf("array:[ ");
for(int i = 0; i < count; i++)
{
printf("%d ", array_num[i]);
}
printf("]\n");
}
int main(void)
{
int count = NUM_COUNT;
// 产生随机数
int * array_num = malloc(sizeof(int) * count);
if(!array_num)
{
perror("malloc");
exit(EXIT_FAILURE);
}
get_random_num(array_num, count);
// 创建线程1,对前半部分符合要求的数据求和
pthread_t child_thread_1;
thread_arg arg1 =
{
.array_num = array_num,
.count = count,
.is_front = true
};
if(pthread_create(&child_thread_1, NULL, thread_function, &arg1) != 0)
{
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 创建线程2,对后半部分符合要求的数据求和
pthread_t child_thread_2;
thread_arg arg2 =
{
.array_num = array_num,
.count = count,
.is_front = false
};
if(pthread_create(&child_thread_2, NULL, thread_function, &arg2) != 0)
{
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 创建线程3,对前半部分符合要求的数据求和,使用互斥量
pthread_t child_thread_3;
thread_arg arg3 =
{
.array_num = array_num,
.count = count,
.is_front = true
};
if(pthread_create(&child_thread_3, NULL, thread_function_with_mutex, &arg3) != 0)
{
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 创建线程4,对后半部分符合要求的数据求和,使用互斥量
pthread_t child_thread_4;
thread_arg arg4 =
{
.array_num = array_num,
.count = count,
.is_front = false
};
if(pthread_create(&child_thread_4, NULL, thread_function_with_mutex, &arg4) != 0)
{
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 创建线程5,对前半部分符合要求的数据求和,使用互斥量和局部变量
pthread_t child_thread_5;
thread_arg arg5 =
{
.array_num = array_num,
.count = count,
.is_front = true
};
if(pthread_create(&child_thread_5, NULL, thread_function_with_mutex_and_local, &arg5) != 0)
{
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 创建线程6,对后半部分符合要求的数据求和,使用互斥量和局部变量
pthread_t child_thread_6;
thread_arg arg6 =
{
.array_num = array_num,
.count = count,
.is_front = false
};
if(pthread_create(&child_thread_6, NULL, thread_function_with_mutex_and_local, &arg6) != 0)
{
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 主线程在此等待所有背景线程结束
if(pthread_join(child_thread_1, NULL) != 0)
{
perror("pthread_join");
exit(EXIT_FAILURE);
}
if(pthread_join(child_thread_2, NULL) != 0)
{
perror("pthread_join");
exit(EXIT_FAILURE);
}
if(pthread_join(child_thread_3, NULL) != 0)
{
perror("pthread_join");
exit(EXIT_FAILURE);
}
if(pthread_join(child_thread_4, NULL) != 0)
{
perror("pthread_join");
exit(EXIT_FAILURE);
}
if(pthread_join(child_thread_5, NULL) != 0)
{
perror("pthread_join");
exit(EXIT_FAILURE);
}
if(pthread_join(child_thread_6, NULL) != 0)
{
perror("pthread_join");
exit(EXIT_FAILURE);
}
printf("[Task #2] Calculate sum by thread: %lu\n", sum);
printf("[Task #2] Calculate sum accurately: %lu\n", calculate_sum(array_num, count));
printf("[Task #3] Calculate sum by thread with mutex: %lu\n", sum_with_mutex);
printf("[Task #4] Calculate sum by thread with mutex and local variable: %lu\n", sum_with_mutex_and_local);
return EXIT_SUCCESS;
}
相关推荐
操作不能完成 (错误 0x00000709) 共享打印机无法连接解决办法
环境:windows Server 2012 + Win10 客户端 问题:使用计算机名和IP地址可以正常连接打印机,但是使用另外的A记录或CN记录无法连接,报此错误 原因:这是打印服务DNS解析的问题 故障补充:假设你的服务器电脑名称叫print01,但是你又建了一条A记录或者CNname 叫PR01,就会发现使用额外的A记录或CN记录就无法连接 故障截图: 操作不能完成 (错误...
linux多线程游戏代码,Linux多线程(示例代码)
一个线程的生命周期起始于它被创建的那一刻,创建线程的接口:#include int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);函数说明:POSIX thread 简称 pthreadpthread_t 是 unsigned lon...
无线自组织网络基础知识
参考书籍:《无线自组织网络路由协议及应用》 目录第一章 绪论1.1 无线自组织网络概述1.1.1 无线自组织网络的定义及分类1.1.2无线自组织网络的主要特点1.1.3无线自组织网络的应用与发展1.无线自组织网络的应用2.无线自组织网络的起源和发展1.2典型的无线自组织网络1.2.1移动Ad Hoc网络1、移动Ad Hoc网络的定义2.移动AdHoc网络的特点3.移动Ad Hoc网络的应用1.2....
Linux下多线程基础编程实例(1)
实例是在网上看到的,大意如下: 有一个全局变量flag, 在main()函数中创建两个线程,去改变这个全局变量的值,要使得线程2等待线程1退出后再退出;当flag 的值从2变为1的时候,主函数再退出; 其实这个例子不太难,了解一些线程相关的函数。 #include #include #include #include #include void *task1(void
永磁同步电机高效标定技术:从理论到实践的全面解析
本文全面解析永磁同步电机高效标定技术,从MTPA标定、弱磁区优化到初始角校准,详细介绍了理论原理和实战技巧。针对新能源汽车应用场景,提供标定系统集成要点和AI辅助优化方案,帮助工程师提升电机性能标定效率与精度。
超分辨率重建:ESPCN与SRGAN技术对比
超分辨率重建:ESPCN与SRGAN技术对比 人工智能,计算机视觉,大模型,AI,超分辨率重建是一种通过技术手段,将低分辨率图像转换为高分辨率图像的过程。它的目的是恢复低分辨率图像中丢失的细节信息,使图像具有更高的清晰度和视觉质量。
Linux 多线程开发(附有案例代码)
同一个程序中的所有线程均会独立执行相同程序,且共享同一份全局内存区域,其中包括初始化数据段、未初始化数据段,以及堆内存段。(传统意义上的UNIX进程只是多线程程序的一个特例,该进程只包含一个线程)调用fork()来创建进程的代价相对较高,即便利用写时复制技术,仍热需要复制诸如内存页表和文件描述符表之类的多种进程属性,这意味着fork()调用在时间上的开销依然不菲。进程间的信息难以共享。由于除去只读代码段外,父子进程并未共享内存,因此必须采用一些进程间通信方式,在进程间进行信息交换。进程ID和父进程工D。..
VCS NLP 低功耗验证系列(六):功耗分析与优化——SAIF 报告与验证效率提升
本文是VCS NLP低功耗验证系列的第六篇,主要解决功耗数据采集和验证效率优化问题。文章首先介绍了SAIF(Switching Activity Interchange Format)文件在功耗分析中的作用,详细讲解了VCS的Region-Based SAIF功能,包括三个关键系统任务($saif_region_create、$saif_region_exclude、$saif_region_monitor)的使用方法和工程实践建议。接着从编译侧、运行侧和方法学侧三个维度提出了NLP验证效率优化策略,特别强
linux 多线程编程例子
线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题: 是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能: 1)有一int型全局变量g_Flag初始值为0; 2) 在主线称中起动线程1,打印“this is thread1”,并将g_Flag设
Win10 开机突然蓝屏错误代码0xc0000001安全模式也进不了,不用重装系统怎么修复?(已解决)九个解决参考方案
Win 10专业版HP480G7。
某联达OA任意用户登录漏洞复现
由于`/WebService/Lk6SyncService/DirectToOthers/GetSSOStamp.asm`j接口未作限制,导致可以通过该接口调用`admin`的`cookie`值,通过对`LoginCredence`和`LoginTimestamp`的参数修改,进而实现任意登录进去系统.
Linux下多线程编程简单示例
最近尝试下Linux下使用多线程开发程序,在百度文库中找到了一段比较好的范例,介绍的很全面,拿出来和大家分享。 Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux下pthread的实现是通过系统调用clone()来实现的。clone(
基于STM32设计的水质检测系统_333
水质安全对生态环境、农业生产、工业制造以及人类健康至关重要。针对传统水质检测方式检测周期长、成本高、实时性差的问题,本项目设计并实现了一种基于STM32的水质检测系统。系统采用STM32F103RCT6作为主控芯片,集成水温、pH值、电导率和浊度等传感器,能够实时采集水质数据,并通过OLED显示屏进行本地显示。同时,利用Air724UG 4G模块通过MQTT协议将数据上传至华为云IoT平台,实现远程监测。用户可通过Qt5开发的Android手机APP和Windows上位机查看水质数据,并接收超限报警提示。此
linux多进程实例代码,linux c多线程编程实例代码
#include #include #include #include #include #define MAX 3int number =0;pthread_t id[2];pthread_mutex_t mut; //初始化静态互斥锁void thread1(void){int i;printf("Hello,I am pthread1!\n");for (i=0; i{pthread_mut...
WINCC7.3破解文件
WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!
pscad IEEE标准系统搭建说明
pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。
基于linux体统多线程代码,linux c多线程编程示例代码
#include #include #include #include #include #define MAX 3int number =0;pthread_t id[2];pthread_mutex_t mut; //初始化静态互斥锁void thread1(void){int i;printf("Hello,I am pthread1!\n");for (i=0; i{pthread_mut...
精雕软件(JDpaint) 5.5 绿色版
精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版
c语言——【linux】多线程编程 (内附练习及代码)
分支线程负责:计算三角形的面积(自己百度海伦公式) 海伦公式里面要用到开平方 sqrt函数,使用sqrt函数编译的时候需要在编译的最后加上 -lm。要求:一定保证1号子进程先读取,2号子进程后读取。这里随便怎么整,一定保证先输入数据,再计算面积。主线程中:使用标准IO,向一个文件中写入任意数据。3:创建一个线程(1个主线程和一个分支线程)分支线程:使用标准IO,读取该文件中的数据。2个子进程负责:从文件中读取数据。主线程负责:输入三角形的三条变长。父进程负责:向文件中写入数据。
RU DOS版、EFI版32bit/64bit BIOS常用工具
DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。
c主线程如何等待子线程结束 linux_Linux 多线程编程入门 (代码)
来源优快云:优快云-专业IT技术社区-登录blog.youkuaiyun.com代码(跟着代码来学习):Linux多线程各个函数示例代码.zip-嵌入式代码类资源-优快云下载download.youkuaiyun.com一、基础知识 进程我前面已经讲解过了,其实进程就是一个的程序文件加载到了内存,然后在内存中创建--运行--消亡的过程 而线程是进程里面的,在C/C++中main函数可以理解为是一个进...
Linux多线程编程——C语言常用函数及代码
收集整理了Linux系统中多线程编程的常用函数及其作用
Linux C 编程项目教程
Linux C 编程项目教程 项目介绍 linux-c 是一个专注于 Linux 环境下 C 语言编程的开源项目。该项目旨在提供一套完整的 C 语言编程资源,包括常用函数库、示例代码、以及相关的开发工具。通过这个项目,开发者可以快速上手 Linux 下的 C 语言编程,并掌握系统编程的基本技能。 项目快速启动 环境准备 在开始之前,请确保你的系统已经安装了以下工具: Git GCC Make ...
ex7编译linux程序,Linux C编程从入门到精通 光盘 源代码 刘学勇
【实例简介】Linux C编程从入门到精通 光盘 源代码 刘学勇【实例截图】【核心代码】sample└── sample├── chapter1│ ├── test│ │ ├── 11.txt│ │ ├── 1.txt│ │ ├── 2.txt│ │ ├── 3.txt│ │ ├── 4.txt│ │ ├── 55.txt│ │ └── ...
嵌入式linux源码,linux示例代码 - 源码下载|嵌入式/单片机编程|嵌入式Linux|源代码 - 源码中国...
linux示例代码\examples\buttons\main.clinux示例代码\examples\buttons\Makefilelinux示例代码\examples\c++\cplus.c++linux示例代码\examples\c++\Makefilelinux示例代码\examples\hello\hello.clinux示例代码\examples\hello\Makefilelinu...
【多线程编程】线程与线程锁的案例讲解
摘要:本文介绍了多线程编程中的线程概念与线程锁机制。通过罗志祥时间管理的生动例子说明线程提高效率的原理,详细讲解了自旋锁和互斥锁的区别与应用场景。在Linux环境下使用pthread库实现了三种线程操作模式(无锁、互斥锁、自旋锁)的对比案例,展示了线程锁对共享变量的保护作用。代码编译需链接POSIX线程库(-lpthread),运行结果显示无锁模式会导致任务丢失,验证了线程锁的必要性。
Linux下多线程编程遇到的一些问题
今天在学习了Linux的多线程编程的基础的知识点。于是就试着做了一个简单的Demo。本以为会得到预期的结果。不成想却遇到了意想不到的问题。代码展示我的C 代码很简单,就是一个简单的示例程序,如下:#include <stdio.h> #include <stdlib.h> #include<pthread.h>int sum ; void* runner(void *param);int main
linux c++ 服务器端开发面试必看书籍
linux c++ 服务器端开发面试必看书籍 打算慢慢把这些书看完。 题外话: 推荐一个 github 上的 开源书籍,有各种语言版本的,建议看 英文版 ,当然也有 中文版 非常之棒!! 一、算法基础系列 数据结构基础(C语言版)》朱仲涛 译 《剑指Offer》 《编程之美》 《编程珠玑》 《CareerCup-Top 150 Questions 4th》 《[算法导论].(美国)Cormen.扫...
linux下的C语言开发(多线程编程)
linux下的C语言开发(多线程编程)
3万+



被折叠的 条评论
为什么被折叠?



