zl程序教程

您现在的位置是:首页 >  系统

当前栏目

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

Linux多线程 简单 一个 例子 浅析 互斥
2023-06-13 09:15:03 时间
复制代码代码如下:

#include<stdio.h>
#include<pthread.h>
pthread_mutex_tDevice_mutex;
intcount=0;
voidthread_func1()
{
  while(1)
  {
      pthread_mutex_lock(&Device_mutex);
      printf("thread1:%d\n",count);
      pthread_mutex_unlock(&Device_mutex);
      count++;
      sleep(1);
  }
}
voidthread_func2()
{
  while(1)
  {
      pthread_mutex_lock(&Device_mutex);
      printf("thread2:%d\n",count);
      pthread_mutex_unlock(&Device_mutex);
      count++;
      sleep(1);
  }
}
intmain()
{
  pthread_tthread1,thread2;
  pthread_mutex_init(&Device_mutex,NULL);
  if(pthread_create(&thread1,NULL,(void*)thread_func1,NULL)==-1)
 {
  printf("createIP81Threaderror!\n");
  exit(1);
 }
 sleep(1);
 if(pthread_create(&thread2,NULL,(void*)thread_func2,NULL)==-1)
 {
  printf("createIP81_2Threaderror!\n");
  exit(1);
 }
 sleep(1);
 pthread_join(thread1,NULL);
 pthread_join(thread2,NULL);
 pthread_mutex_destroy(&Device_mutex);
 return0;
}