栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

linux C语言 多线程竞争(加锁解锁 pthread

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

linux C语言 多线程竞争(加锁解锁 pthread

参考文章:Linux C语言 多线程竞争实例以及简单解决办法

线程在短时间内对相同内存单元进行操作时,如果不加锁解锁,有可能产生线程竞争的情况,即最终结果不符合预期

示例:

test_pthread_compete.c

#include 
#include 
#include 
#include 
 
static long unsigned int count = 0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
 
static void *funcAdd(void *arg){
	pthread_mutex_lock(&mylock);
	count++;
	pthread_mutex_unlock(&mylock);
	sleep(1);
	pthread_mutex_lock(&mylock);
	count++;
	pthread_mutex_unlock(&mylock);
	sleep(1);
	pthread_mutex_lock(&mylock);
	count++;
	pthread_mutex_unlock(&mylock);
	pthread_exit(NULL);
}
 
static void *funcAdd_nolock(void *arg){
	count++;
	sleep(1);
	count++;
	sleep(1);
	count++;
	pthread_exit(NULL);
}
 
int main(){
 
	pthread_t tid[1024];
	int i, j;
 
//不加锁
	for(i = 0; i < 1000; i++){
		if(pthread_create(&tid[i], NULL, funcAdd_nolock, NULL) != 0){
			perror("pthread_create()");
			//for(j = 0; j < i; j++){
			//	pthread_join(tid[i], NULL);
			//}			
		}
	}
 
	for(i = 0; i < 1000; i++){
		pthread_join(tid[i], NULL);
	}
 
	printf("if without lock, count = %ldn", count);
	count = 0;
//加锁
	for(i = 0; i < 1000; i++){
		if(pthread_create(&tid[i], NULL, funcAdd, NULL) != 0){
			perror("pthread_create()");
			//for(j = 0; j < i; j++){
			//	pthread_join(tid[i], NULL);
			//}
		}
	}
 
	for(i = 0; i < 1000; i++){
		pthread_join(tid[i], NULL);
	}
 
	printf("if has lock, count = %ldn", count);
 
 
	exit(0);
}

ubuntu上编译:

gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo &&  ./test_pthread_compete 

运行结果:

[root@ubuntu /arnold_test/20220721_test_pthread]15# gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo &&  ./test_pthread_compete 

if without lock, count = 2935
if has lock, count = 3000
[root@ubuntu /arnold_test/20220721_test_pthread]16# gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo &&  ./test_pthread_compete 

if without lock, count = 2935
if has lock, count = 3000
[root@ubuntu /arnold_test/20220721_test_pthread]17# gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo &&  ./test_pthread_compete 

if without lock, count = 2943
if has lock, count = 3000

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1026117.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号