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

 时间:2024-10-12 14:40:34

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怎么用
  • 热门搜索
    今天股市为什么大跌 镉怎么读 平行四边形怎么画 为什么叫孩子为神兽 神经衰弱怎么调理 宕怎么读 怎么缩阴 鹿晗为什么退出exo 雒怎么读姓氏 昱字怎么读