I am confused how to use Mutex using POSIX. Consider the following code:
void *print_message_function( void *ptr );
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
main()
{
pthread_t thread1, thread2,thread3;
std::string message1 = "Apple";
std::string message2 = "Orange";
int iret1, iret2,iret3;
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) &message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) &message1);
iret3 = pthread_create( &thread3, NULL, print_message_function, (void*) &message2);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
pthread_join( thread3, NULL);
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
pthread_mutex_lock( &count_mutex );
int i = 3 ;
while( i ) {
printf("i is %d ...%s \n", i,(*(std::string *)ptr).c_str() );
i-- ;
sleep (1) ;
}
pthread_mutex_unlock( &count_mutex );
}
Thread1 and thread 2 use a common resource -- message1. Thread3 uses own resource -- message 3. Messing up printing on STDOUT is OK for me.
The output of the program is
i is 3 ...Apple
i is 2 ...Apple
i is 1 ...Apple
i is 3 ...Apple
i is 2 ...Apple
i is 1 ...Apple
i is 3 ...Orange
i is 2 ...Orange
i is 1 ...Orange
As we see thread3 is executed at the end. Since thread3 doesn't use any common resource, how can I make it "skip the mutex lock". How can I make a mutex lock enable only when two threads are accessing a common piece of memory and not otherwise. Mutex must be dynamic. I am open to even specifying a variable which shouldn't point to same location in memory for the lock to be activated. In other words, how can I make a mutex that gets activated only when two threads collide.
I understand this might be a duplicate question. But I was unable to find any solution for this problem. Also, due to some environment restrictions, I cant use C++11 STL threads or boost. I would like help in pthreads library.