当前位置: 首页 > article >正文

C语言I/O请使用互斥锁和信号量分别实现5个线程之间的同步

1.代码运行结果:

2.源码解析:

        使用互斥锁: pthread_mutex_t mutex;:定义一个互斥锁。 pthread_mutex_init(&mutex, NULL);:初始化互斥锁。 pthread_mutex_lock(&mutex);:在临界区前加锁,确保同一时间只有一个线程可以进入临界区。 pthread_mutex_unlock(&mutex);:在临界区后解锁,允许其他线程进入临界区。 pthread_mutex_destroy(&mutex);:销毁互斥锁。

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

#define NUM_THREADS 5

// 互斥锁
pthread_mutex_t mutex;

void* thread_function(void* arg) {
    int thread_id = *(int*)arg;

    // 加锁
    pthread_mutex_lock(&mutex);

    printf("线程 %d 正在执行\n", thread_id);

    // 模拟一些工作
    for (int i = 0; i < 1000000; i++);

    printf("线程 %d 执行完毕\n", thread_id);

    // 解锁
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main(int argc, const char *argv[]) 
{
    pthread_t threads[NUM_THREADS];
    int thread_args[NUM_THREADS];

    // 初始化互斥锁
    pthread_mutex_init(&mutex, NULL);

    for (int i = 0; i < NUM_THREADS; i++) {
        thread_args[i] = i;
        pthread_create(&threads[i], NULL, thread_function, &thread_args[i]);
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    // 销毁互斥锁
    pthread_mutex_destroy(&mutex);

    return 0;
}

        使用信号量: sem_t semaphore;:定义一个信号量。 sem_init(&semaphore, 0, 1);:初始化信号量,初始值为1,表示资源可用。 sem_wait(&semaphore);:等待信号量,如果信号量的值大于0,则减1并继续执行;如果信号量的值为0,则阻塞等待。 sem_post(&semaphore);:释放信号量,信号量的值加1,唤醒等待的线程。 sem_destroy(&semaphore);:销毁信号量。

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

#define NUM_THREADS 5

// 信号量
sem_t semaphore;

void* thread_function(void* arg) {
    int thread_id = *(int*)arg;

    // 等待信号量
    sem_wait(&semaphore);

    printf("线程 %d 正在执行\n", thread_id);

    // 模拟一些工作
    for (int i = 0; i < 1000000; i++);

    printf("线程 %d 执行完毕\n", thread_id);

    // 释放信号量
    sem_post(&semaphore);

    pthread_exit(NULL);
}

int main(int argc, const char *argv[]) 
 {
    pthread_t threads[NUM_THREADS];
    int thread_args[NUM_THREADS];

    // 初始化信号量,初始值为1
    sem_init(&semaphore, 0, 1);

    for (int i = 0; i < NUM_THREADS; i++) {
        thread_args[i] = i;
        pthread_create(&threads[i], NULL, thread_function, &thread_args[i]);
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    // 销毁信号量
    sem_destroy(&semaphore);

    return 0;
}


http://www.kler.cn/a/520769.html

相关文章:

  • java求职学习day17
  • 1.26学习
  • 2025年01月26日Github流行趋势
  • Python3 【正则表达式】:经典示例参考手册
  • 寒假1.25
  • 第04章 15 vtkObjectBase和vtkObject的基本特性及它们在VTK类体系中基础性作用
  • 动手学图神经网络(4):利用图神经网络进行图分类
  • 云岚到家项目100问 v1.0
  • 二叉树高频题目——下——不含树型dp
  • 基于单片机的智能小区门禁系统设计(论文+源码)
  • 【填充——双指针,DP】
  • 【算法】剪枝与优化
  • java复习总结
  • 有赞任务js脚本
  • C#的反射使用示例
  • c++小知识点
  • 从规则到神经网络:机器翻译技术的演进与未来展望
  • Golang 执行流程分析
  • 「 机器人 」扑翼飞行器的偏航力矩控制:分周期参数调节机制
  • 【SpringMVC】——Json数据交互处理