局部锁和全局锁的区别

1、单线程的锁用局部锁,锁不住其他线程的访问

#include <stdio.h>
#include <pthread.h>

typedef struct {
	int num;
	char array[20];
} PthreadTestPara_t;
PthreadTestPara_t p_struct[20] = {0};


int g_num = 0;
void *PthreadGetDataFromArray(void *argv)
{
	PthreadTestPara_t  *p = (PthreadTestPara_t *)argv;
	pthread_mutex_t lock;//改成全局变量就不一样了
	pthread_mutex_lock(&lock);

	printf("pthread[%x] : num : %d\n", (unsigned int)pthread_self(), p->num);
	
	g_num = p->num;
	printf("pthread[%x] : g_num : %d\n",  (unsigned int)pthread_self(), g_num);
	sleep(3 * p->num);
	pthread_mutex_unlock(&lock);

}

int main()
{
	pthread_t pid;
	int i = 0;
	for (i = 0; i < 5; i++) {
		p_struct[i].num = i;
		pthread_create(&pid, NULL, PthreadGetDataFromArray, (void *)&(p_struct[i]));
		pthread_detach(pid);
	}
	sleep(50);
	return 0;
}

最终结果如下:
pthread[b6592b40] : num : 2
pthread[b6592b40] : g_num : 2
pthread[b6d93b40] : num : 1
pthread[b6d93b40] : g_num : 1
pthread[b5d91b40] : num : 3
pthread[b5d91b40] : g_num : 3
pthread[b5590b40] : num : 4
pthread[b5590b40] : g_num : 4

说明该锁没有作用。其他线程还是可以访问的,将该锁改成全局的,用的是一把锁,效果就如下:
pthread[b75d0b40] : num : 0
pthread[b75d0b40] : g_num : 0
pthread[b6dcfb40] : num : 1
pthread[b6dcfb40] : g_num : 1
pthread[b65ceb40] : num : 2
pthread[b65ceb40] : g_num : 2
pthread[b5dcdb40] : num : 3
pthread[b5dcdb40] : g_num : 3
pthread[b55ccb40] : num : 4
pthread[b55ccb40] : g_num : 4

临界资源的访问,锁的加入是为了确定谁用使用权。 照上面的测试结果,谁对临界资源的使用权判断,是靠一把锁来确定的,而且始终是这把锁。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值