C言語でスレッドロックを書く

スレッドのロックは、C言語では、ミューテックス(mutex)やスピンロック(spinlock)といった仕組みが一般的に用いられています。以下は、ミューテックスによるスレッドロックの実装例です。

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

// 定义全局互斥量
pthread_mutex_t mutex;

// 线程函数
void* thread_func(void* arg) {
    // 加锁
    pthread_mutex_lock(&mutex);

    // 临界区代码
    printf("Thread %ld is running\n", pthread_self());

    // 解锁
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main() {
    // 初始化互斥量
    pthread_mutex_init(&mutex, NULL);

    pthread_t thread1, thread2;

    // 创建两个线程
    pthread_create(&thread1, NULL, thread_func, NULL);
    pthread_create(&thread2, NULL, thread_func, NULL);

    // 等待线程结束
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

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

    return 0;
}

スレッド関数では、クリティカルセクションコードをロックで保護し、一度に 1 つのスレッドしかクリティカルセクションにアクセスできないようにしています。

排他制御をスレッドロックで実装する場合は、排他制御のロック解除操作にpthread_spin_lockとpthread_spin_unlock関数が使用できます。排他制御とスレッドロックの適用シーンはわずかに異なり、スレッドロックは多コア環境でより効果を発揮しますが、シングルコア環境ではスレッドがずっとスレッドロックにかかり続けて実行する機会がない可能性があります。

bannerAds