Linux Next example of a simple multithreaded mutex

Source: Internet
Author: User
Tags mutex printf sleep thread
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;
}

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.