C語(yǔ)言中,線程鎖的實(shí)現(xiàn)通常使用互斥量(mutex)或者自旋鎖(spinlock)。下面是使用互斥量實(shí)現(xiàn)線程鎖的示例代碼:
#include <stdio.h>
#include <pthread.h>
// 定義全局互斥量
pthread_mutex_t mutex;
// 線程函數(shù)
void* thread_func(void* arg) {
// 加鎖
pthread_mutex_lock(&mutex);
// 臨界區(qū)代碼
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;
// 創(chuàng)建兩個(gè)線程
pthread_create(&thread1, NULL, thread_func, NULL);
pthread_create(&thread2, NULL, thread_func, NULL);
// 等待線程結(jié)束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// 銷毀互斥量
pthread_mutex_destroy(&mutex);
return 0;
}
上述代碼中使用了pthread_mutex_lock
函數(shù)進(jìn)行加鎖操作,pthread_mutex_unlock
函數(shù)進(jìn)行解鎖操作。在線程函數(shù)中,臨界區(qū)代碼被加鎖保護(hù),確保同一時(shí)間只能有一個(gè)線程訪問(wèn)臨界區(qū)。
如果要使用自旋鎖實(shí)現(xiàn)線程鎖,可以使用pthread_spin_lock
和pthread_spin_unlock
函數(shù)替代互斥量的加鎖解鎖操作。需要注意的是,互斥量和自旋鎖適用的場(chǎng)景略有不同,自旋鎖在多核環(huán)境下效果更好,在單核環(huán)境下可能導(dǎo)致線程一直自旋而沒(méi)有機(jī)會(huì)執(zhí)行。