【多线程同步】

江南北

关注

阅读 31

04-18 09:00

在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来查看效果。

精彩评论(0)

0 0 举报