Linux Next example of a simple multithreaded mutex

Source: Internet
Author: User
Tags mutex printf sleep
This article is an example of a simple multithreaded mutex in Linux analysis, the need for friends can refer to the following copy code code as follows:


#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)
   {
     & nbsp 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;
}

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.