Linux系统下POSIX互斥锁用法

Linux下所有线程是并发执行、异步执行,当不同线程对同一资源进行操作时,就要涉及线程同步问题,使得在同一时间该资源只能被一个线程占用,其它线程必须等待或返回。

原子操作:当所有线程对同一资源进行同步访问时,可以引入锁(互斥锁和读写锁);获得锁的线程可以完成对该资源的“读-修改-写”3步操作,要么都执行,要么都不执行,不会中间被打断,也不会再其它处理器上并行做这个操作。这三步操作就叫做原子操作。

一、本文主要总结POSIX下互斥锁用法,具体用法如下所述:

1.1互斥锁概念

是线程同步的一种机制,用来保护多线程的共享资源,同一时刻,只允许一个线程对临界区进行访问。

1.2创建步骤

(1)创建一个互斥锁对象:(静态创建和动态创建)

静态创建:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

动态创建:

pthread_mutex_t *pmutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(pmutex,NULL);

(2)初始化一个互斥锁:在进入临界区前把互斥锁加锁(防止其它线程进入临界区)

pthread_mutex_t *pmutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(pmutex,NULL);

(3)解锁互斥锁:退出临界区时解锁互斥锁,让别的线程有机会进入临界区;

pthread_mutex_unlock(pmutex);
//或者
pthread_mutex_unlock(&mutex);    //pmutex是一个指针变量

(4)销毁互斥锁:不用的时候销毁该互斥锁,回收资源。

pthread_mutex_destroy(pmutex);
//或者
pthread_mutex_destroy(&mutex);    //pmutex是一个指针变量

 

二、POSIX下互斥锁调用实例(功能:用互斥锁多线程累加)

2.1在Linux指定目录下新建一个文件名为test.cpp的空白文件,在其中添加如下代码:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h> 
#include <string.h>
#include <cstdlib>
 
int gcn = 0;

pthread_mutex_t mutex;
	
void *thread_1(void *arg) {
	int j;
	for (j = 0; j < 10000000; 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 < 10000000; j++) {
		pthread_mutex_lock(&mutex);  
		gcn++;
		pthread_mutex_unlock(&mutex); 
	}  
	pthread_exit((void *)0);
}
int main(void) 
{
	int j,err;
	pthread_t th1, th2;
	 
	pthread_mutex_init(&mutex, NULL); 
	for (j = 0; j < 10; j++)
	{
		err = pthread_create(&th1, NULL, thread_1, (void *)0);
		if (err != 0) {
			printf("create new thread error:%s\n", strerror(err));
			exit(0);
		}  
		err = pthread_create(&th2, NULL, thread_2, (void *)0);
		if (err != 0) {
			printf("create new thread error:%s\n", strerror(err));
			exit(0);
		}  
           
		err = pthread_join(th1, NULL);
		if (err != 0) {
			printf("wait thread done error:%s\n", strerror(err));
			exit(1);
		}
		err = pthread_join(th2, 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;
}

2.2在终端输入如下命令,结果如图所示:

g++ -o test test.cpp -lpthread

 

 

参考内容:

《Linux C与C++ 一线开发实践》 朱文伟,李建英著. -北京:清华大学出版社,2018  406-440页

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三公子Tjq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值