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;
}