Linux 多线程 互斥锁 浅析Linux下一个简单的多线程互斥锁的例子

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Linux 多线程 互斥锁 浅析Linux下一个简单的多线程互斥锁的例子

  2021-03-18 我要评论
想了解浅析Linux下一个简单的多线程互斥锁的例子的相关内容吗,在本文为您仔细讲解Linux 多线程 互斥锁的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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: %d\n",count);
       pthread_mutex_unlock(&Device_mutex);
       count++;
       sleep(1);
   }
}
void thread_func2()
{
   while(1)
   {
       pthread_mutex_lock(&Device_mutex);
       printf("thread2: %d\n",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;
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们