栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux无名信号量(semaphore)

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

Linux无名信号量(semaphore)

头文件:

 
 
 

编译:添加 -lpthread 选项
示例:gcc -lpthread code.c -o a.out

#include 
#include 
#include 
#include 
#include 
#include 
#include 

unsigned int number = 0;

void* thread1(void* para);	//线程1服务函数
void* thread2(void* para);	//线程2服务函数

int main(int argc, char** argv)
{
	pthread_t threadID1, threadID2;
	int ret = 0;

	ret = pthread_create(&threadID1, NULL, thread1, NULL);	//创建线程1
	if(ret)
	{
		printf("Thread1 create failed!n");
		exit(EXIT_FAILURE);
	}

	ret = pthread_create(&threadID2, NULL, thread2, NULL);	//创建线程2
	if(ret)
	{
		printf("Thread2 create failed!n");
		exit(EXIT_FAILURE);
	}

	pthread_join(threadID1, NULL);	//等待线程thread1结束
	pthread_join(threadID2, NULL);	//等待线程thread2结束
	ptherad_exit((void*)0);			//退出现场main

	return 0;
}

void* thread1(void* para)
{
	printf("Function thread1 running...n");
	
	while(1)
	{
		number = 100;
		sleep(1);
		printf("number: %un", number);
	}

	pthread_exit((void*)0);
}

void* thread2(void* para)
{
	unsigned int count = 0;
	printf("Function thread2 running...n");
	
	while(1)
	{
		count++;
		number = count;
	}

	pthread_exit((void*)0);
}


结果分析:没有二元信号量的约束,线程thread1对number的赋值几乎不会等于100,原因是线程thread2对number的访问导致的。

#include 
#include 
#include 
#include 
#include 
#include 
#include 

unsigned int number = 0;
sem_t semID;

void* thread1(void* para);
void* thread2(void* para);

int main(int argc, char** argv)
{
	pthread_t threadID1, threadID2;
	int ret = 0;

	ret = pthread_create(&threadID1, NULL, thread1, NULL);
	if(ret)
	{
		printf("Thread1 create failed!n");
		exit(EXIT_FAILURE);
	}

	ret = pthread_create(&threadID2, NULL, thread2, NULL);
	if(ret)
	{
		printf("Thread2 create failed!n");
		exit(EXIT_FAILURE);
	}

	ret = sem_init(&semID, 0, 1);
	if(ret == -1)
	{
		printf("Sem create failed!n");
		exit(EXIT_FAILURE);
	}

	pthread_join(threadID1, NULL);
	pthread_join(threadID2, NULL);
	ptherad_exit((void*)0);

	return 0;
}

void* thread1(void* para)
{
	printf("Function thread1 running...n");
	
	while(1)
	{
		sem_wait(&semID);	//等待信号量
		number = 100;
		sleep(1);
		printf("number: %un", number);
		sem_post(&semID);	//释放信号量
	}

	pthread_exit((void*)0);
}

void* thread2(void* para)
{
	unsigned int count = 0;
	printf("Function thread2 running...n");
	
	while(1)
	{
		sem_wait(&semID);
		count++;
		number = count;
		sem_post(&semID);
	}

	pthread_exit((void*)0);
}


结果分析:加入信号量后,不管是线程thread1还是线程thread2对number的访问都不能同时进行,对全局变量number进行了很好的保护。

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

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

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