温馨提示×

c语言线程锁如何写

小亿
106
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