In the previous post, a simple example of using shared locks was given.This post introduces a slightly more complex example.
There is a global variable array out containing 100 elements, all initialized to zero.Then open two sub-threads to assign the array out at the same time.In this process, shared locks should be enabled to synchronize the assignment code.The code is as follows:
#include <stdio.h> #include <pthread.h> pthread_mutex_t number_mutex; //Out array is a global variable, all 100 elements are initialized to zero, two threads together assign values to out array int out[100]; //Thread 1 void thread1() { int i; while(1){ printf("Thread 1 operated.\n"); pthread_mutex_lock(&number_mutex); for(i=0;i<100;i++){ if(out[i]==0){ //Elements that have not been assigned are assigned out[i]=1111; break; } } //If the last element has been assigned, unlock and exit the thread if(out[99]!=0) { pthread_mutex_unlock(&number_mutex); return; } pthread_mutex_unlock(&number_mutex); } } //Thread 2 void thread2() { int i; while(1){ printf("Thread 2 operated.\n"); pthread_mutex_lock(&number_mutex); for(i=0;i<100;i++){ if(out[i]==0){ out[i]=2222; break; } } if(out[99]!=0) { pthread_mutex_unlock(&number_mutex); return; } pthread_mutex_unlock(&number_mutex); } } main() { //Initialize 100 elements of an out array int i; for(i=0;i<100;i++){ out[i]=0; } pthread_t thid1,thid2; printf("This is Main Thread.\n"); pthread_mutex_init(&number_mutex,NULL); pthread_create(&thid1,NULL,thread1,NULL); pthread_create(&thid2,NULL,thread2,NULL); int status1,status2; pthread_join(thid1,(void*)&status1); pthread_join(thid2,(void*)&status2); pthread_mutex_destroy(&number_mutex); //Output Array New Value for 100 Elements for(i=0;i<100;i++){ printf("%d, ",out[i]); } printf("\nMain Thread exit\n"); }
The results are as follows:
2 threads run alternately, assigning all 100 array elements new values.