【多线程同步】

在C语言中,使用pthread库来实现多线程并保证线程同步。下面的示代码,创建两个线程并保证它们同步执行:

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

// 定义互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 线程函数1
void *thread_func1(void *arg) {
    // 对mutex加锁
    pthread_mutex_lock(&mutex);
    printf("Thread 1 is running\n");
    // 模拟耗时操作
    sleep(2);
    printf("Thread 1 is done\n");
    // 解锁mutex
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

// 线程函数2
void *thread_func2(void *arg) {
    // 对mutex加锁
    pthread_mutex_lock(&mutex);
    printf("Thread 2 is running\n");
    // 模拟耗时操作
    sleep(2);
    printf("Thread 2 is done\n");
    // 解锁mutex
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main() {
    pthread_t tid1, tid2;

    // 创建线程1
    pthread_create(&tid1, NULL, thread_func1, NULL);
    // 创建线程2
    pthread_create(&tid2, NULL, thread_func2, NULL);

    // 等待线程1和线程2结束
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    printf("All threads are done\n");

    return 0;
}

在这个示例代码中,首先定义了一个互斥锁mutex,然后在线程函数中使用pthread_mutex_lockpthread_mutex_unlock来保证线程同步。在主函数中,我们创建了两个线程分别执行thread_func1thread_func2,并通过pthread_join等待这两个线程结束后再继续执行主线程。

将上述代码保存到一个.c文件中(比如multi_thread_sync.c),然后使用以下命令来编译并运行程序:

gcc -o multi_thread_sync multi_thread_sync.c -pthread
./multi_thread_sync

下面是一个示例bash脚本,可以阻塞SIGINT信号的传递,并在程序中对其同步处理:

#!/bin/bash

# 定义处理信号的函数
handler() {
    echo "Received SIGINT signal, handling it..."
    # 在这里处理SIGINT信号
}

# 阻塞SIGINT信号
trap 'handler' INT

# 无限循环
while true
do
    echo "Running..."
    sleep 1
done

在这个脚本中,使用trap 'handler' INT语句来阻塞SIGINT信号的传递,并将处理函数handler与该信号关联。当程序接收到SIGINT信号时,将执行handler函数中定义的处理逻辑。

将上述代码保存到一个脚本文件中(比如block_signal.sh),然后通过chmod +x block_signal.sh来赋予执行权限,并执行脚本./block_signal.sh来查看效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贺公子之数据科学与艺术

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值