Search code examples
cunixpthreadsmutexerrno

pthread_mutex_trylock() in Linux


I am learning to use mutex in Linux programming. I came across trylock function, which first checks for the mutex if it is available it locks it otherwise, it return.

Now my question is:

  • Does it return after reaching the end of function without executing the critical section, when trylock is called?
  • Why doesn't it is printing errno in my code below?

Here is the code:

int main()
{
pthread_t tid[5];

int i;

if(pthread_mutex_init(&mutex,NULL))
    printf("Failed to lock the mutex\n");
for(i=0;i<5;i++)
{
    if(pthread_create(&tid[i],NULL,func,&i))
        printf("Failed to create a thread\n");

    if(errno==EBUSY)
        printf("thread busy\n");

}

for(i=0;i<5;i++)
{
    if(pthread_join(tid[i],NULL))
        printf("Failed to wait for thread %d\n",i);
}

printf("All threads terminated\n");

return 0;
}

void *func(void * arg)
{
int i=*(int *)arg;

if(pthread_mutex_trylock(&mutex)==0)
{
    sleep(5);
printf(" i is %d\n",i);

pthread_mutex_unlock(&mutex);
}
else
    if(errno== EBUSY)
            printf("thread busy\n");
}

Sorry for format less code..

Regards


Solution

  • pthread_mutex_trylock() doesn't set errno - you simply use the return value:

    int result = pthread_mutex_trylock(&mutex);
    
    if(result==0)
    {
        sleep(5);
        printf(" i is %d\n",i);
    
        pthread_mutex_unlock(&mutex);
    }
    else
        if (result == EBUSY)
                printf("thread busy\n");
    }