我是靠谱客的博主 开心溪流,这篇文章主要介绍Linux下一个简单的多线程互斥锁的例子,现在分享给大家,希望可以做个参考。

#include <stdio.h>
#include <pthread.h>
pthread_mutex_t Device_mutex ;
int count=0;
void thread_func1()
{
   while(1)
   {
       pthread_mutex_lock(&Device_mutex);
       printf("thread1: %dn",count);
       pthread_mutex_unlock(&Device_mutex);
       count++;
       sleep(1);
   }

}

void thread_func2()
{
   while(1)
   {
       pthread_mutex_lock(&Device_mutex);
       printf("thread2: %dn",count);
       pthread_mutex_unlock(&Device_mutex);
       count++;
       sleep(1);
   }
}

int main()
{

   pthread_t thread1, thread2;
   pthread_mutex_init(&Device_mutex,NULL);

   if(pthread_create(&thread1,NULL,(void*)thread_func1,NULL) == -1)
	{
		printf("create IP81 Thread error !n");
		exit(1);
	}
	sleep(1);
	if(pthread_create(&thread2,NULL,(void *)thread_func2,NULL) == -1)
	{
		printf("create IP81_2 Thread error!n");
		exit(1);
	}
	sleep(1);
	pthread_join(thread1,NULL);
	pthread_join(thread2,NULL);
	pthread_mutex_destroy(&Device_mutex);

	return 0;
}

最后

以上就是开心溪流最近收集整理的关于Linux下一个简单的多线程互斥锁的例子的全部内容,更多相关Linux下一个简单内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(113)

评论列表共有 0 条评论

立即
投稿
返回
顶部