讲师中心 微信公众号
AI工具推荐 视频效率加速

掌握 C 编程中的多线程:深入讲解和高级概念

小伟吖_8475

小伟吖_8475

发布时间:2024-07-10 10:35:12

|

322人浏览过

|

来源于dev.to

转载

掌握 c 编程中的多线程:深入讲解和高级概念

介绍:

C 编程中的多线程使开发人员能够充分利用现代多核处理器的潜力,促进单个进程中任务的并发执行。本综合指南探讨了基本的多线程概念、同步机制和高级主题,为每个概念提供了详细的解释和示例代码。

1. 理解线程:

线程是进程内独立的执行序列,允许并发执行任务。了解线程的创建、管理和状态对于有效的多线程处理至关重要。

线程创建:
pthread_create():初始化一个新线程并开始执行。
pthread_join():等待线程终止后再继续。

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

无效*threadFunc(无效*arg){
    printf("来自新线程的你好!n");
    pthread_exit(NULL);
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, threadFunc, NULL);
    pthread_join(tid, NULL);
    printf("回到主线程.n");
    返回0;
}

2、同步与互斥:

当多个线程同时访问共享资源时,会出现竞争条件,从而导致不可预测的行为。互斥体、信号量、条件变量等同步机制保证线程安全。

互斥体(互斥):
互斥体提供互斥,一次只允许一个线程访问共享资源。它们可以防止数据损坏并确保行为一致。

#include <stdio.h>
#include <pthread.h>
pthread_mutex_t 互斥体 = PTHREAD_MUTEX_INITIALIZER;
int 共享变量 = 0;

无效*threadFunc(无效*arg){
    pthread_mutex_lock(&mutex);
    共享变量++;
    printf("线程将共享变量增加到:%dn",共享变量);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
    }

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, threadFunc, NULL);
    pthread_mutex_lock(&mutex);
    共享变量--;
    printf("主线程将共享变量递减为:%dn",共享变量);
    pthread_mutex_unlock(&mutex);
    pthread_join(tid, NULL);
    返回0;
}

信号量:
信号量是用于控制对共享资源的访问并协调多个线程的执行的同步原语。他们维护一个计数来限制同时访问资源的线程数量。

#include <stdio.h>
#include <pthread.h>
#include <信号量.h>

sem_t 信号量;

无效*threadFunc(无效*arg){
    sem_wait(&信号量);
    printf("线程获取信号量");
    // 临界区
    sem_post(&信号量);
    pthread_exit(NULL);
}

int main() {
    pthread_t tid;
    sem_init(&信号量, 0, 1); // 用值 1 初始化信号量
    pthread_create(&tid, NULL, threadFunc, NULL);
    // 主线程
    sem_wait(&信号量);
    printf("主线程获取信号量");
    // 临界区
    sem_post(&信号量);
    pthread_join(tid, NULL);
    返回0;
}

3、线程通信:

线程通信有利于线程之间的协调和同步。条件变量允许线程等待满足特定条件。

条件变量:
条件变量使线程能够等待特定条件的发生。它们通常用于生产者-消费者场景,其中线程在继续之前等待数据可用性。

#include <stdio.h>
#include <pthread.h>
pthread_mutex_t 互斥体 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condVar = PTHREAD_COND_INITIALIZER;
int 数据就绪 = 0;

无效*生产者(无效*参数){
    pthread_mutex_lock(&mutex);
    数据就绪=1;
    pthread_cond_signal(&condVar);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

无效*消费者(无效*参数){
    pthread_mutex_lock(&mutex);
    while (!dataReady) {
        pthread_cond_wait(&condVar, &mutex);
    }
    printf("消费者:数据已准备好!n");
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main() {
    pthread_t 生产者线程,消费者线程;
    pthread_create(&生产者线程,NULL,生产者,NULL);
    pthread_create(&consumerThread, NULL, 消费者, NULL);
    pthread_join(生产者线程,NULL);
    pthread_join(consumerThread, NULL);
    返回0;
}

4. 先进概念:

优先级反转、饥饿、死锁和自旋锁等高级主题对于构建健壮的多线程应用程序至关重要。

优先级反转:
当低优先级线程持有高优先级线程所需的资源时,就会发生优先级反转,从而导致优先级反转。优先级继承协议通过暂时将低优先级线程的优先级提高到高优先级线程的优先级来帮助缓解此问题。

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

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;

无效*highPriorityThread(无效*arg){
    pthread_mutex_lock(&mutex1);
    pthread_mutex_lock(&mutex2);
    // 执行高优先级任务
    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    pthread_exit(NULL);
}

无效*lowPriorityThread(无效*arg){
    pthread_mutex_lock(&mutex2);
    pthread_mutex_lock(&mutex1);
    // 执行低优先级任务
    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);
    pthread_exit(NULL);
}

int main() {
    pthread_t 高优先级,低优先级;
    pthread_create(&highPrioTid, NULL, highPriorityThread, NULL);
    pthread_create(&lowPrioTid, NULL, lowPriorityThread, NULL);
    pthread_join(highPrioTid, NULL);
    pthread_join(lowPrioTid, NULL);
    返回0;
}

饥饿:
当一个线程由于其他线程不断获取所需资源而无法访问这些资源时,就会发生饥饿。公平的调度策略确保所有线程都有公平的资源分配机会,防止饥饿。

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

pthread_mutex_t 互斥体 = PTHREAD_MUTEX_INITIALIZER;
int 共享资源 = 0;

无效*threadFunc(无效*arg){
    pthread_mutex_lock(&mutex);
    // 增加共享资源
    共享资源++;
    printf("线程将共享资源增加到:%dn",共享资源);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main() {
    pthread_t tid1, tid2;

    // 创建两个线程
    pthread_create(&tid1, NULL, threadFunc, NULL);
    pthread_create(&tid2, NULL, threadFunc, NULL);

    // 等待两个线程完成
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    // 主线程
    pthread_mutex_lock(&mutex);
    // 访问共享资源
    printf("主线程访问了sharedResource:%dn",sharedResource);
    pthread_mutex_unlock(&mutex);

    返回0;
}

死锁:
当两个或多个线程无限期地等待对方释放它们所需的资源时,就会发生死锁。避免循环等待并实施死锁检测和恢复机制有助于缓解死锁情况。

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

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;

无效*线程1(无效*参数){
    pthread_mutex_lock(&mutex1);
    pthread_mutex_lock(&mutex2);
    // 临界区
    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    pthread_exit(NULL);
}

无效*线程2(无效*参数){
    pthread_mutex_lock(&mutex2);
    pthread_mutex_lock(&mutex1);  // 潜在的死锁点
    // 临界区
    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);
    pthread_exit(NULL);
}

int main() {
    pthread_t tid1,tid2;
    pthread_create(&tid1, NULL, thread1, NULL);
    pthread_create(&tid2, NULL, thread2, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    返回0;
}

自旋锁:
自旋锁是同步原语,其中线程不断轮询资源的可用性。它们对于短关键部分和低争用场景非常有效。

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

pthread_spinlock_t 自旋锁;

无效*threadFunc(无效*arg){
    pthread_spin_lock(&spinlock);
    // 临界区
    printf("线程获得了自旋锁n");
    // 执行一些任务
    pthread_spin_unlock(&spinlock);
    pthread_exit(NULL);
}

int main() {
    pthread_t tid1, tid2;
    pthread_spin_init(&spinlock, 0);
    pthread_create(&tid1, NULL, threadFunc, NULL);
    pthread_create(&tid2, NULL, threadFunc, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_spin_destroy(&spinlock);
    返回0;
}

结论:

掌握 C 编程中的多线程需要深入理解基本概念、同步机制和高级主题。通过深入研究这些概念并探索示例代码,开发人员可以构建健壮、高效且响应迅速的多线程应用程序。持续实践、实验和遵守最佳实践是精通多线程和开发充分利用现代硬件功能的可靠软件系统的关键。

热门AI工具

更多
蛙蛙写作

一款AI论文写作工具,主要用于超级AI智能写作助手,适合需要提升相关任务效率的用户。

切问学术

切问学术是一款AI论文写作工具,复旦大学NLP团队推出的AI学术智能体。

Atoms
Atoms Hot

Atoms是一款AI智能体工具,第一支自动构建真实业务的 AI 团队。

立刻MV
立刻MV Hot

立刻MV是一款AI文本写作工具,AI 音乐视频(MV)创作工具。

PixPix
PixPix Hot

PixPix是一款面向电商视觉生产的AI商品图生成工具。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

Loomy
Loomy Hot

一款AI工具,主要用于科大讯飞发布的桌面级 AI 助理,比 OpenClaw 更易用、更安全!,适合需要提升相关任务效率的用户。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

相关专题

更多
线程和进程的区别
线程和进程的区别

线程和进程的区别:线程是进程的一部分,用于实现并发和并行操作,而线程共享进程的资源,通信更方便快捷,切换开销较小。本专题为大家提供线程和进程区别相关的各种文章、以及下载和课程。

4318

2023.08.10

Python 多线程与异步编程实战
Python 多线程与异步编程实战

本专题系统讲解 Python 多线程与异步编程的核心概念与实战技巧,包括 threading 模块基础、线程同步机制、GIL 原理、asyncio 异步任务管理、协程与事件循环、任务调度与异常处理。通过实战示例,帮助学习者掌握 如何构建高性能、多任务并发的 Python 应用。

1209

2025.12.24

java多线程相关教程合集
java多线程相关教程合集

本专题整合了java多线程相关教程,阅读专题下面的文章了解更多详细内容。

403

2026.01.21

C++多线程相关合集
C++多线程相关合集

本专题整合了C++多线程相关教程,阅读专题下面的的文章了解更多详细内容。

559

2026.01.21

C# 多线程与异步编程
C# 多线程与异步编程

本专题深入讲解 C# 中多线程与异步编程的核心概念与实战技巧,包括线程池管理、Task 类的使用、async/await 异步编程模式、并发控制与线程同步、死锁与竞态条件的解决方案。通过实际项目,帮助开发者掌握 如何在 C# 中构建高并发、低延迟的异步系统,提升应用性能和响应速度。

389

2026.02.06

C++多线程并发控制与线程安全设计实践
C++多线程并发控制与线程安全设计实践

本专题围绕 C++ 在高性能系统开发中的并发控制技术展开,系统讲解多线程编程模型与线程安全设计方法。内容包括互斥锁、读写锁、条件变量、原子操作以及线程池实现机制,同时结合实际案例分析并发竞争、死锁避免与性能优化策略。通过实践讲解,帮助开发者掌握构建稳定高效并发系统的关键技术。

233

2026.03.16

Java 多线程与并发编程实战
Java 多线程与并发编程实战

深入讲解 Java 并发编程体系,涵盖 Thread / Runnable / Callable 线程创建方式、线程生命周期与状态转换、synchronized 同步锁与 Lock/ReentrantLock 显式锁、volatile 可见性保证、ThreadPool 线程池配置与调优(核心参数/拒绝策略)、JUC 并发工具类(CountDownLatch/CyclicBarrier/Semaphore/ConcurrentHashMa

349

2026.04.17

C++ 多线程使用教程大全
C++ 多线程使用教程大全

系统讲解 C++11 及后续标准引入的多线程编程能力,涵盖 std::thread 线程创建与生命周期管理、std::mutex / shared_mutex 互斥锁与读写锁、std::condition_variable 条件变量同步、std::atomic 原子操作与内存序(memory_order)、std::future / promise / async 异步任务、线程池的设计与实现、死锁检测与避免策略,帮助开发者编写正确高效

216

2026.04.28

Gradle插件开发入门教程
Gradle插件开发入门教程

本专题介绍Gradle插件开发的基本流程,涵盖插件类编写、自定义任务注册、扩展参数设计和插件应用方法,帮助你理解插件如何组织构建逻辑,减少多个项目之间的重复配置。

20

2026.10.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
RabbitMQ 入门教程
RabbitMQ 入门教程

共0课时 | 140人学习

Elasticsearch中文手册
Elasticsearch中文手册

共0课时 | 0人学习

mysql8主从复制原理底层详解
mysql8主从复制原理底层详解

共1课时 | 706人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn