c语言线程锁如何写

   2025-02-15 3430
核心提示:C语言中,线程锁的实现通常使用互斥量(mutex)或者自旋锁(spinlock)。下面是使用互斥量实现线程锁的示例代码:#include stdio

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函数替代互斥量的加锁解锁操作。需要注意的是,互斥量和自旋锁适用的场景略有不同,自旋锁在多核环境下效果更好,在单核环境下可能导致线程一直自旋而没有机会执行。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言