溫馨提示×

c語言線程鎖如何寫

小億
158
2023-11-23 12:14:41
欄目: 編程語言

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;
}

上述代碼中使用了pthread_mutex_lock函數進行加鎖操作,pthread_mutex_unlock函數進行解鎖操作。在線程函數中,臨界區代碼被加鎖保護,確保同一時間只能有一個線程訪問臨界區。

如果要使用自旋鎖實現線程鎖,可以使用pthread_spin_lockpthread_spin_unlock函數替代互斥量的加鎖解鎖操作。需要注意的是,互斥量和自旋鎖適用的場景略有不同,自旋鎖在多核環境下效果更好,在單核環境下可能導致線程一直自旋而沒有機會執行。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女