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

所属分类: 操作系统 / unix linux 阅读数: 60
收藏 0 赞 0 分享
复制代码 代码如下:

#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;
}
更多精彩内容其他人还在看

linux网站建立步骤

linux网站建立步骤
收藏 0 赞 0 分享

linux系统如何访问NTFS磁盘

linux系统如何访问NTFS磁盘
收藏 0 赞 0 分享

简单高效:用Swatch做Linux日志分析

简单高效:用Swatch做Linux日志分析
收藏 0 赞 0 分享

全球顶尖超级计算机60%用Linux系统

全球顶尖超级计算机60%用Linux系统
收藏 0 赞 0 分享

Linux操作系统12则经典应用技巧

Linux操作系统12则经典应用技巧
收藏 0 赞 0 分享

Linux 的 常 用 网 络 命 令

Linux 的 常 用 网 络 命 令
收藏 0 赞 0 分享

循序渐进学习LINUX之软件配置

循序渐进学习LINUX之软件配置
收藏 0 赞 0 分享

混合使用Linux和Windows

混合使用Linux和Windows
收藏 0 赞 0 分享

浅谈linux操作系统的优化及安全

浅谈linux操作系统的优化及安全
收藏 0 赞 0 分享

如何实现Linux操作系统的自动登录

如何实现Linux操作系统的自动登录
收藏 0 赞 0 分享
查看更多