According to the man pages
pthread_mutex_lock locks the given mutex. If the mutex is currently unlocked, it becomes locked and owned by the calling thread, and pthread_mutex_lock returns immediately. If the mutex is already locked by another thread, pthread_mutex_lock suspends the calling thread until the mutex is unlocked.
What I understood is when line 3
executes the main thread
has ownership of the mtx
. It then performs its critcal region actions and then reaches line 4
and unlocks mtx
. My question is -
- Can the other thread concurrently run when
mtx
is locked? - What is the use of
line 2
sincenewThread
can only unlockmtx
whenline 4
has been executed, and thus makesline 2
redundant? What would happen if
line 1
is uncommented?#include<stdio.h> #include<pthread.h> #include<semaphore.h> #include<unistd.h> sem_t bin_sem; pthread_mutex_t mtx; char message[100]; void * thread_function(void * arg) { int x; char message2[10]; while(1) { // pthread_mutex_lock(&mtx); //line 1 printf("thread2 : waiting..\n\n"); sem_wait(&bin_sem); printf("hi i am the new thread waiting inside critical..\n"); scanf("%s",message); printf("You entered in newthread:%s\n\n",message); sem_post(&bin_sem); pthread_mutex_unlock(&mtx); //line 2 } } int main(void) { pthread_t athread; pthread_attr_t ta; char message2[10]; int x; sem_init(&bin_sem,0,1); pthread_mutex_init(&mtx,NULL); pthread_attr_init(&ta); pthread_attr_setschedpolicy(&ta,SCHED_RR); pthread_create(&athread,&ta,thread_function,NULL); while(1) { pthread_mutex_lock(&mtx); //line 3 printf("main waiting..\n\n"); sem_wait(&bin_sem); printf("hi i am the main thread waiting inside critical..\n"); scanf("%s",message); printf("You entered in main:%s\n\n",message); sem_post(&bin_sem); pthread_mutex_unlock(&mtx); //line 4 } sleep(5); }