Matt
Matt

Reputation: 173

two threads, first adds second substracts

This is a classic example of mutex locks. I don't know why the following code doesn't work, ie. it doesn't print "ctr = 0" every time (but, for example, ctr = 535).

int ctr;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

void * add (void * arg_wsk)
{
        int i;
        for (i = 0; i < 100000; i++) {
                pthread_mutex_lock (&m);
                ctr++;
                pthread_mutex_unlock (&m);
        }
        return(NULL);
}

void * sub(void * arg_wsk)
{
        int i;
        for (i = 0; i < 100000; i++) {
                pthread_mutex_lock (&m);
                ctr--;
                pthread_mutex_unlock (&m);
        }
        return(NULL);
}
int main()
{       
        pthread_t tid1, tid2;
        int i;
        void *res;
        ctr = 0;
        pthread_mutex_init(&m, NULL);

        pthread_create(&tid1, NULL, add, NULL);
        pthread_detach(tid1);

        pthread_create(&tid2, NULL, sub, NULL);
        pthread_detach(tid2);

        pthread_join(tid1, &res);
        pthread_join(tid2, &res);

        pthread_mutex_destroy(&m);
        printf("ctr = %d", ctr);
        pthread_exit(NULL);
}

Upvotes: 1

Views: 58

Answers (2)

user124493
user124493

Reputation:

I think you are misusing the POSIX API. If you detach the threads, you shouldn't join them. Remove the detach and see if this improves things. I think you'll see that main() now blocks until the threads have completed.

Note also, from the link for the join call

ESRCH  No  thread could be found corresponding to that specified by the
          given thread ID.

If you're lucky, you'll hit this. If you're not lucky, crazy things will happen. Don't mix detach and join calls on the same thread.

https://computing.llnl.gov/tutorials/pthreads/#Joining

Upvotes: 4

HAL
HAL

Reputation: 3998

The value of your counter ctr depends on both the threads completing their full execution.

According to pthread_detach(3)

Once a thread has been detached, it can't be joined with pthread_join(3) or be made joinable again.

If you remove pthread_detach call from your program, you will get the expected output.

Also, consider explicitly creating your thread joinable(or detached) for portability.

Upvotes: 1

Related Questions