C语言中的多线程编程如何实现?_c 多线程编程-程序员宅基地

技术标签: java  c语言  C语言100问  开发语言  

C语言多线程编程详解

多线程编程是一种在计算机程序中同时执行多个线程(子任务)的编程技术,它可以提高程序的并发性和性能。在C语言中,多线程编程通常通过标准库中的pthread库来实现。本文将详细介绍C语言中多线程编程的基本概念、线程的创建和管理、线程同步与通信以及一些常见的多线程编程模式。

第一部分:多线程编程基本概念

1.1 什么是线程?

线程是一个程序内部的执行单元,每个线程都有自己的执行路径和上下文。一个进程可以包含多个线程,这些线程可以并发执行,共享进程的内存空间和资源,但拥有各自的栈空间和寄存器状态。

1.2 为什么使用多线程?

多线程编程有以下优点:

  • 并发性:多线程使程序可以同时执行多个任务,提高了程序的并发性,可以更充分地利用多核处理器。
  • 响应性:多线程可以使程序响应用户输入或外部事件,保持界面的活跃性。
  • 资源共享:多线程允许线程之间共享内存和资源,可以降低资源消耗,提高效率。
  • 模块化:多线程可以将复杂任务分解为多个独立的线程,使程序更易于维护和扩展。

1.3 线程的生命周期

线程的生命周期包括以下阶段:

  • 创建:线程通过调用创建函数创建,此时线程处于可运行状态。
  • 运行:线程被调度执行,处于运行状态。
  • 阻塞:线程可能在等待某个事件或资源时进入阻塞状态,不占用CPU时间。
  • 终止:线程执行完任务或发生错误时,进入终止状态。

第二部分:多线程编程的实现

2.1 多线程库

在C语言中,多线程编程通常使用pthread库(POSIX Threads)来实现。pthread库提供了一组函数和数据结构,用于创建、管理和同步线程。要使用pthread库,需要在编译时链接-lpthread标志。

2.2 线程的创建

在C语言中,使用pthread_create函数来创建新线程。以下是pthread_create函数的基本用法:

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine)(void *), void *arg);
  • thread:用于存储新线程的标识符。
  • attr:线程属性,通常可以设置为NULL
  • start_routine:新线程的入口函数,该函数接受一个void*参数并返回void*
  • arg:传递给start_routine的参数。

下面是一个简单的示例,演示如何创建一个新线程:

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

void *print_hello(void *arg) {
    printf("Hello from new thread!\n");
    return NULL;
}

int main() {
    pthread_t tid; // 线程标识符
    pthread_create(&tid, NULL, print_hello, NULL);
    pthread_join(tid, NULL); // 等待新线程结束
    printf("Main thread: New thread has finished.\n");
    return 0;
}

在上面的示例中,pthread_create函数创建了一个新线程,该线程执行print_hello函数。pthread_join函数用于等待新线程的结束。

2.3 线程的退出

线程可以通过pthread_exit函数主动退出,也可以通过从线程函数中返回退出。以下是两种方式的示例:

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

void *exit_thread(void *arg) {
    printf("Thread will exit using pthread_exit.\n");
    pthread_exit(NULL); // 主动退出线程
}

void *return_thread(void *arg) {
    printf("Thread will exit by returning from thread function.\n");
    return NULL; // 返回退出线程
}

int main() {
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, exit_thread, NULL);
    pthread_create(&tid2, NULL, return_thread, NULL);
    
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    
    printf("Main thread: All threads have finished.\n");
    return 0;
}

在上面的示例中,两种方式都可以用来退出线程,但需要注意线程的资源管理,以免出现内存泄漏。

2.4 线程的传参和返回值

线程的入口函数可以接受一个参数,并返回一个值。要向线程传递参数,可以将参数打包为一个结构体,并通过void*传递。要从线程函数返回值,可以将返回值作为指针传递给线程函数,并在函数内部修改该指针指向的值。

以下是一个示例,演示如何向线程传递参数并获取返回值:

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

// 结构体用于传递参数和接收返回值
typedef struct {
    int a;
    int b;
} ThreadParams;

void *add_numbers(void *arg) {
    ThreadParams *params = (ThreadParams *)arg;
    int result = params->a + params->b;
    return (void *)(intptr_t)result; // 将结果作为指针返回
}

int main() {
    pthread_t tid;
    ThreadParams params = {5, 3};
    void *retval; // 存储线程的返回值

    pthread_create(&tid, NULL, add_numbers, &params);
    pthread_join(tid, &retval); // 获取线程的返回值

    int result = (int)(intptr_t)retval; // 将返回值转换为整数
    printf("Result: %d\n", result);

    return 0;
}

2.5 线程的销毁

线程在完成任务后可以通过pthread_exit来正常退出,也可以使用pthread_cancel函数来取消线程的执行。要注意线程取消可能会引发一些资源管理的问题,因此需要小心使用。

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

void *cancel_thread(void *arg) {
    printf("Thread will be canceled.\n");
    pthread_cancel(pthread_self()); // 取消当前线程
    printf("Thread is still running after cancel.\n");
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, cancel_thread, NULL);
    pthread_join(tid, NULL);
    printf("Main thread: Thread has finished.\n");
    return 0;
}

在上面的示例中,线程在自身内部调用pthread_cancel来取消自己的执行。

第三部分:线程同步与通信

3.1 互斥锁

多个线程访问共享资源时可能导致竞态条件,为了避免竞态条件,可以使用互斥锁(Mutex)。互斥锁允许一个线程在访问共享资源时锁定它,其他线程必须等待解锁后才能访问。

以下是互斥锁的基本用法:

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 初始化互斥锁

void *increment(void *arg) {
    for (int i = 0; i < 1000000; i++) {
        pthread_mutex_lock(&mutex); // 锁定互斥锁
        // 访问共享资源
        pthread_mutex_unlock(&mutex); // 解锁互斥锁
    }
    return NULL;
}

int main() {
    pthread_t tid1, tid2;
    
    pthread_create(&tid1, NULL, increment, NULL);
    pthread_create(&tid2, NULL, increment, NULL);
    
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    
    printf("Main thread: All threads have finished.\n");
    
    return 0;
}

在上面的示例中,两个线程分别执行increment函数,通过互斥锁来保护对共享资源的访问。

3.2 条件变量

条件变量(Condition Variable)用于在线程之间进行通信,它允许一个线程等待另一个线程满足某个条件后再继续执行。通常与互斥锁一起使用。

以下是条件变量的基本用法:

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

void *waiter(void *arg) {
    pthread_mutex_lock(&mutex);
    printf("Waiter: Waiting for signal...\n");
    pthread_cond_wait(&condition, &mutex); // 等待条件变量
    printf("Waiter: Received signal. Continuing...\n");
    pthread_mutex_unlock(&mutex);
    return NULL;
}

void *signaler(void *arg) {
    sleep(2); // 等待2秒
    printf("Signaler: Signaling...\n");
    pthread_cond_signal(&condition); // 发送信号
    return NULL;
}

int main() {
    pthread_t tid1, tid2;
    
    pthread_create(&tid1, NULL, waiter, NULL);
    pthread_create(&tid2, NULL, signaler, NULL);
    
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    
    printf("Main thread: All threads have finished.\n");
    
    return 0;
}

在上面的示例中,waiter线程等待条件变量,而signaler线程在2秒后发送信号,唤醒等待线程。

3.3 读写锁

读写锁(Read-Write Lock)用于控制多线程对共享数据的读写访问。多个线程可以同时读取共享数据,但只有一个线程可以写入数据。读写锁可以提高程序的并发性,适用于读多写少的场景。

以下是读写锁的基本用法:

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

pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

void *reader(void *arg) {
    pthread_rwlock_rdlock(&rwlock); // 读取锁
    printf("Reader: Reading data...\n");
    pthread_rwlock_unlock(&rwlock); // 解锁
    return NULL;
}

void *writer(void *arg) {
    pthread_rwlock_wrlock(&rwlock); // 写入锁
    printf("Writer: Writing data...\n");
    pthread_rwlock_unlock(&rwlock); // 解锁
    return NULL;
}

int main() {
    pthread_t tid1, tid2;
    
    pthread_create(&tid1, NULL, reader, NULL);
    pthread_create(&tid2, NULL, writer, NULL);
    
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    
    printf("Main thread: All threads have finished.\n");
    
    return 0;
}

在上面的示例中,reader线程获取读取锁,而writer线程获取写入锁,以模拟多个读取线程和一个写入线程的情况。

第四部分:常见的多线程编程模式

4.1 生产者-消费者模式

生产者-消费者模式是一种常见的多线程编程模式,用于解决生产者线程和消费者线程之间的协作问题。生产者线程生成数据并将其放入缓冲区,而消费者线程从缓冲区中获取数据并进行处理。

以下是一个简单的生产者-消费者示例:

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

#define BUFFER_SIZE 5

int buffer[BUFFER_SIZE];
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;

void *producer(void *arg) {
    for (int i = 0; i < 10; i++) {
        sleep(1); // 模拟生产过程
        pthread_mutex_lock(&mutex);
        while (count == BUFFER_SIZE) {
            pthread_cond_wait(&empty, &mutex); // 等待缓冲区非满
        }
        buffer[count++] = i;
        printf("Producer: Produced %d\n", i);
        pthread_cond_signal(&full); // 通知消费者缓冲区非空
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

void *consumer(void *arg) {
    for (int i = 0; i < 10; i++) {
        sleep(1); // 模拟消费过程
        pthread_mutex_lock(&mutex);
        while (count == 0) {
            pthread_cond_wait(&full, &mutex); // 等待缓冲区非空
        }
        int item = buffer[--count];
        printf("Consumer: Consumed %d\n", item);
        pthread_cond_signal(&empty); // 通知生产者缓冲区非满
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
    pthread_t producer_tid, consumer_tid;
    
    pthread_create(&producer_tid, NULL, producer, NULL);
    pthread_create(&consumer_tid, NULL, consumer, NULL);
    
    pthread_join(producer_tid, NULL);
    pthread_join(consumer_tid, NULL);
    
    printf("Main thread: All threads have finished.\n");
    
    return 0;
}

在上面的示例中,生产者线程和消费者线程使用互斥锁和条件变量来同步,确保缓冲区的正确访问。

4.2 线程池

线程池是一种管理线程的机制,它预先创建一组线程并维护一个任务队列。当有任务需要执行时,线程池从队列中获取一个空闲线程并将任务分配给它。

以下是一个简单的线程池示例:

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

#define THREAD_COUNT 4
#define TASK_COUNT 10

typedef struct {
    int task_id;
} Task;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t task_available = PTHREAD_COND_INITIALIZER;

void *worker(void *arg) {
    while (1) {
        pthread_mutex_lock(&mutex);
        while (/* 任务队列为空 */) {
            pthread_cond_wait(&task_available, &mutex);
        }
        // 从任务队列中获取任务
        // 执行任务
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
    pthread_t threads[THREAD_COUNT];
    
    // 创建线程池
    for (int i = 0; i < THREAD_COUNT; i++) {
        pthread_create(&threads[i], NULL, worker, NULL);
    }
    
    // 向线程池添加任务
    for (int i = 0; i < TASK_COUNT; i++) {
        Task task = {i};
        pthread_mutex_lock(&mutex);
        // 将任务添加到队列
        pthread_cond_signal(&task_available); // 通知线程池有任务可用
        pthread_mutex_unlock(&mutex);
    }
    
    // 等待线程池中的线程执行完所有任务
    for (int i = 0; i < THREAD_COUNT; i++) {
        pthread_join(threads[i], NULL);
    }
    
    printf("Main thread: All tasks have been completed.\n");
    
    return 0;
}

在上面的示例中,线程池由多个线程组成,它们等待任务队列中的任务并执行。主线程向线程池添加任务,并等待线程池中的线程执行完所有任务。

第五部分:多线程编程的注意事项

5.1 竞态条件

多线程编程容易引发竞态条件(Race Condition),即多个线程同时访问共享资源,导致不可预测的结果。为了避免竞态条件,需要使用互斥锁等同步机制。

5.2 死锁

死锁(Deadlock)是多线程编程中常见的问题,它发生在多个线程互相等待对方释放资源的情况下。要避免死锁,需要小心设计线程的同步和资源管理策略。

5.3 数据共享与保护

多线程共享数据时需要注意数据的一致性和完整性。使用互斥锁、读写锁等机制来保护共享数据,确保线程安全。

5.4 性能与扩展性

多线程编程可以提高程序的并发性和性能,但也可能引入线程管理开销。要权衡性能和扩展性,避免创建过多线程。

第六部分:总结

多线程编程是C语言中的重要编程技术,它允许程序同时执行多个任务,提高了程序的并发性和性能。通过了解线程的创建、退出、传参和返回值,以及线程同步与通信的机制,你可以编写多线程程序来解决各

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_68551689/article/details/133442414

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签