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

有帮助吗?

解决方案

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");
}

其他提示

Does it return after reaching the end of function without executing the critical section, when trylock is called?

if pthread_mutex_trylock(&mutex) is successfull (i.e. it returns 0) then first part (i.e. critical section) would be executed and function will return. if pthread_mutex_trylock(&mutex) is unsuccessful(i.e. it returns -1) then else part would be executed and hopefully thread busy would be printed and function would return without executing critical section.

Why doesn't it is printing errno in my code below?

Either the call to pthread_mutex_trylock(&mutex) is always successful, if you see all values of i (i.e. 1-5) being printed then this is the case. Or the errorno is not EBUSY you can check that by printing something before if(errno== EBUSY).

The documentation for pthread_mutex_trylock says it returns the error code if locking the mutex cannot be done, it doesn't set errno to EBUSY. To get the expected result, you should do e.g.

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

  pthread_mutex_unlock(&mutex);
} else {
  printf("thread busy: %s\n", strerror(rc));
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top