linux线程互斥锁的使用方法及代码测试

 时间:2026-02-12 05:27:53

1、编辑调试代码

#include <stdio.h>

#include <pthread.h>

int global_val = 0;

void *thread1(void *arg){

        while(1){

                global_val = global_val + 1;

                printf("thread1 global_val=%d\n", global_val);

                global_val = global_val + 1;

                usleep(100);

                printf("thread1 global_val=%d\n", global_val);

                usleep(100);

        }

        return NULL;

}

void *thread2(void *arg){

        while(1){

                global_val = global_val + 1;

                printf("thread2 global_val=%d\n", global_val);

                usleep(100);

                global_val = global_val + 1;

                printf("thread2 global_val=%d\n", global_val);

                usleep(100);

        }

        return NULL;

}

linux线程互斥锁的使用方法及代码测试

2、编译测试代码gcc mutex.c -o mutex -lpthread

linux线程互斥锁的使用方法及代码测试

3、查看运行结果,图示位置发现问题。结果不正确。

linux线程互斥锁的使用方法及代码测试

4、上述代码是无锁状态下的运行情况,运行结果与预期的结果不同,出现错误。下面我们加上互斥锁。

#include <stdio.h>

#include <pthread.h>

pthread_mutex_t thread_mutex;

int global_val = 0;

void *thread1(void *arg){

while(1){

pthread_mutex_lock(&thread_mutex);

global_val = global_val + 1;

printf("thread1 global_val=%d\n", global_val);

global_val = global_val + 1;

usleep(100);

                printf("thread1 global_val=%d\n", global_val);

usleep(100);

pthread_mutex_unlock(&thread_mutex);

}

return NULL;

}

void *thread2(void *arg){

while(1){

pthread_mutex_lock(&thread_mutex);

        global_val = global_val + 1;

        printf("thread2 global_val=%d\n", global_val);

                usleep(100);

global_val = global_val + 1;

                printf("thread2 global_val=%d\n", global_val);

        usleep(100);

pthread_mutex_unlock(&thread_mutex);

}

return NULL;

}

int main(void){

pthread_t thread_id1 = 0, thread_id2 = 0;

pthread_mutex_init(&thread_mutex, NULL);

pthread_create(&thread_id1, NULL, thread1, NULL);

pthread_create(&thread_id2, NULL, thread2, NULL);

pthread_join(thread_id1, NULL);

pthread_join(thread_id2, NULL);

return 0;

}

linux线程互斥锁的使用方法及代码测试

5、保存代码后编译。

linux线程互斥锁的使用方法及代码测试

6、运行查看结果,与预期的一致。说明互斥锁起到保护临界资源的作用。

linux线程互斥锁的使用方法及代码测试

  • Jquery要怎样触发某个链接点击事件
  • input输入框标签输入中文、数字、字母的写法
  • java项目右击属性java Build Path等丢失
  • HTML图片像素的设置
  • 网页设计中margin怎么用
  • 热门搜索
    争当美德少年手抄报 文明餐桌手抄报 宪法手抄报图片大全 艾滋病手抄报图片 庆十一手抄报 数学手抄报内容三年级 六一儿童节手抄报内容资料 有关科学的手抄报 防新型冠状病毒手抄报 五四青年节手抄报内容