多线程-互斥锁

  • 并发和异步机制,导致线程之间资源竞争的无序性。
  • 由此,引入同步机制,消除复杂性,实现线程之间的数据共享。

异步的定义是什么?

  • 未搞懂

线程同步

  • 思想:同步各个线程对资源的访问,比如:全局变量、文件。
  • 解决方法:锁,获得锁的线程才能完成读写操作,一个原子操作。
  • 原子操作是未了防止CPU执行计算过程中,多条指令被打断,寄存器的值被修改,导致计算错误。

临界资源&临界区

互斥锁

初始化


上锁

解锁

销毁

代码

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
int gcn = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * thread_1(void *arg)
{
int j;
for (j = 0; j < 100; j++)
{
pthread_mutex_lock(&mutex);
gcn++;
pthread_mutex_unlock(&mutex);
}
pthread_exit((void *)0);
}
void * thread_2(void *arg)
{
int j;
for (j = 0; j < 100; j++)
{
pthread_mutex_lock(&mutex);
gcn++;
pthread_mutex_unlock(&mutex);
}
pthread_exit((void *)0);
}
/* main */
int main(void)
{
pthread_t tid1, tid2;
int err;
pthread_mutex_init(&mutex, NULL);
for (int j = 0; j < 10; j++)
{
err = pthread_create(&tid1, NULL, thread_1, (void *)0);
if (err != 0)
{
perror("error pthread create.\n");
exit(1);
}
else
{
printf("create thread OK.\n");
}
err = pthread_create(&tid2, NULL, thread_2, (void *)0);
if (err != 0)
{
perror("error pthread create.\n");
exit(1);
}
else
{
printf("create thread OK.\n");
}
err = pthread_join(tid1, NULL);
if (err != 0)
{
printf("wait thread done error:%s.\n", strerror(err));
exit(1);
}
err = pthread_join(tid2, NULL);
if (err != 0)
{
printf("wait thread done error:%s.\n", strerror(err));
exit(1);
}
printf("gcn=%d.\n", gcn);
gcn = 0;
}
pthread_mutex_destroy(&mutex);
return 0;
}
posted @   steve的miao  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示