Just look at the code, there's a comment in the code.
Copy Code code as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#define MAX 3
int number = 0;
pthread_t id[2];
pthread_mutex_t Mut; Initializing a static mutex
void Thread1 (void)
{
int i;
printf ("Hello,i am pthread1!\n");
for (i=0 i<max; i++)
{
Pthread_mutex_lock (&mut); //Here is locked to ensure the uniqueness of number
number ++;
printf ("Thread1:number =%d\n", number);
Pthread_mutex_unlock (&mut);
Sleep (1); //linux C (minute), inside variable units is minutes
}
pthread_exit (NULL);/The thread terminates execution by executing this function. Return is a null pointer type
}
void Thread2 (void)
{
Int J;
printf ("Hello,i ' m pthread2\n");
For (j=0 j<max; j + +)
{
Pthread_mutex_lock (&mut);
number + +;
printf ("Thread2:number =%d\n", number);
Pthread_mutex_unlock (&mut);
Sleep (1);
}
Pthread_exit (NULL);
}
void Thread_create (void)
{
int temp;
memset (&id, 0, sizeof (ID));
if (temp = Pthread_create (&id[0], NULL, (void *) thread1, NULL)!= 0)
Parameters: Thread identifier pointer thread property thread run function start Address run Function property
Create successful return 0
printf ("Thread 1 fail to create!\n");
Else
printf ("Thread 1 created\n");
if (temp = Pthread_create (&id[1], NULL, (void *) thread2, NULL)!= 0)
printf ("Thread 2 fail to create!\n");
Else
printf ("Thread 2 created!\n");
}
void Thread_wait ()
{
if (Id[0]!= 0)
{
Pthread_join (Id[0], NULL); Wait for thread to end, use this function to recycle created thread resource
printf ("Thread1 completed!\n");
}
if (Id[1]!= 0)
{
Pthread_join (id[1], NULL);
printf ("Thread2 completed!\n");
}
}
int main (void)
{
int I,ret1,ret2;
Pthread_mutex_init (&mut, NULL); Dynamic Mutual exclusion Lock
printf ("Main fuction,creating thread...\n");
Thread_create ();
printf ("Main fuction, waiting for the Pthread end!\n");
Thread_wait ();
return (0);
}