This experiment created 3 processes, in order to better describe the parallel execution between threads, let 3 threads share the same execution function. Each thread has 5 loops (which can be seen as 5 small tasks), and each cycle is randomly waiting for 1~10s time, meaning that simulating the arrival time of each task is random and does not have any specific rules. Complete mutually exclusive access using mutex mutex
1#include <stdio.h>2#include <stdlib.h>3#include <pthread.h>4 5 #defineThread_number 3//Number of Threads6 #defineRepat_number 5//number of small tasks in each thread7 #defineDelay_time_levels 10.0//the maximum time interval between small tasks8pthread_mutex_t Mutex;//defining a global variable for a single-pane mutex9 Ten //thread function Routines One void*func (void*Arg) A { - intThrd_num= (int) arg; - intDelay_time=0; the intCount=0; - intRes; - //Mutex Lock -Res=pthread_mutex_lock (&mutex); + if(res!=0){ -printf"Thread%d lock failed.\n", thrd_num); + Pthread_exit (NULL); A } at //The following code is the shared area -printf"thread%d is starting\n", thrd_num); - for(count=0; count<repat_number; count++){ -Delay_time= (int) (rand () *delay_time_levels/(Rand_max)) +1; - sleep (delay_time); -printf"\tthread%d:job%d delay%d\n", Thrd_num, Count, delay_time); in } -printf"Thread%d finished\n", thrd_num); to //unlocking the mutex leaves the main thread +Pthread_mutex_unlock (&mutex); -Pthread_exit (NULL);//thread Exits the } * $ intMainintargcChar Const*argv[])Panax Notoginseng { -pthread_t Thread[thread_number];//Store thread ID the intNo,res; + void*Thrd_ret; A Srand (Time (NULL)); the + for(no=0; no<thread_number; no++){ - //Creating Multithreading $Res=pthread_create (&thread[no],null, (void*) Func, (void*) no); $ if(res!=0){ -printf"Create thread%d failed.\n", no); - exit (res); the } - }Wuyi theprintf"create thread success\nwaiting for thread to finish...\n"); - for(no=0; no<thread_number; no++){ Wu //wait for thread to end -Res=pthread_join (thread[no],&Thrd_ret); About if(!Res) { $printf"Thread%d finished\n", no); -}Else{ -printf"thread%d join failed.\n", no); - } A //Mutex lock Unlock + //Pthread_mutex_unlock (&mutex); the } - return 0; $}
View Code
Notice that 32 rows and 62 rows are unlocked, and if you use 32 lines to comment out 62 lines, the program will work
However, if you use 62 lines and comment out 32 lines, the program will be stuck in a certain place, run 8 times, the following second situation only appears 1 times.
An issue that is not raised within a thread by a mutex