user1492588
user1492588

Reputation:

The mutex locks a value in a function for ever

I am new in threads in c. My code has a thread that increasing a counter and occasionally(randomly) another thread reads that counter. I used mutex in this code but my code always gives me value equal to 1. Although I used pthread_mutex_unlock but it seems the value becomes lock for ever. what should I do to solve the problem?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <pthread.h>
///////////////////////////

long int count=0;
int RunFlag=0;
pthread_mutex_t mtx;

void *readfun(void *arg)
{
    while (RunFlag==0)
    {
        pthread_mutex_lock(&mtx);
        count=count+1;
        pthread_mutex_unlock(&mtx);
    }

}
void *printfun(void *arg)
{
    int RadnTime=0;
    for (int j=0;j<4;j++)
    {
        RadnTime=rand()%3+1;
        sleep(RadnTime);

        printf("The current counter after %d seconds is: ",RadnTime);
        pthread_mutex_lock(&mtx);
        printf("%d\n",count);
        pthread_mutex_unlock(&mtx);
    }



}

void main ()
{
    pthread_t thread1;
    pthread_t thread2;

    pthread_mutex_init(&mtx, NULL);

    pthread_create(&thread1,NULL,readfun,NULL);
    pthread_create(&thread2,NULL,printfun,NULL);

    //stop the counter
    RunFlag=1;

    pthread_exit(NULL);
}

Upvotes: 0

Views: 65

Answers (2)

ikegami
ikegami

Reputation: 385645

You are setting RunFlag immediately after the two threads are created, so readfun barely has any time to execute. RunFlag=1; should be at the end of printfun.


As far as I know, reading from and writing to RunFlag isn't guaranteed to be atomic, so access to it should be protected as well. I don't see a problem happening here (given the values in question), but you are entering undefined behaviour territory.


Your functions don't return anything even though they are declared as returning void*. Add return NULL; to them.


Finally, the second %d should be %ld since count is a long int.


Note that

pthread_mutex_t mtx;
pthread_mutex_init(&mtx, NULL);

can be replaced with

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

Upvotes: 1

P.P
P.P

Reputation: 121357

1) You also have data race as two are accessing RunFlag. So, you need to protect it with synchronization primitive (such as mutex or use a semaphore).

But you don't need the RunFlag for this purpose. Since you can use an infinite loop in readfun() thread and then simply call _exit() from printfun() thread to exit the whole process.

2) Thread functions must return a pointer to satisfy by pthread_create()'s requirement. But you thread functions don't return anything. You can add return NULL; at the end of both thread functions.

Be aware of signed integer overflow as count could potentially overflow.

Upvotes: 1

Related Questions