mko
mko

Reputation: 22114

After applying semaphore, the code still doesn't work as expected

The following code should output NITER * 2, but it seems like still no mutex working, any idea?

and why clang gives me the following warning:

semaphore-example-add-semaphore.c:24:1: warning: control reaches end of non-void
      function [-Wreturn-type]
}
^
1 warning generated.

code:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>

#define NITER 1000000

int count = 0;

sem_t mutex;


void * ThreadAdd(void * a)
{
    int i, tmp;
    for(i = 0; i < NITER; i++)
    {
        sem_wait(&mutex);
        tmp = count;
        tmp = tmp + 1;
        count = tmp;
        sem_post(&mutex);
    }
}

int main(int argc, char * argv[])
{
    pthread_t tid1, tid2;
    sem_init(&mutex, 0, 1);
    if(pthread_create(&tid1, NULL, ThreadAdd, NULL))
    {
        printf("\n ERROR create thread 1");
        exit(1);
    }
    if(pthread_create(&tid2, NULL, ThreadAdd, NULL))
    {
        printf("\n ERROR create thread 2");
        exit(1);
    }
    if(pthread_join(tid1, NULL))
    {
        printf("\n error joining thread");
        exit(1);
    }
    if(pthread_join(tid2, NULL))
    {
        printf("\n ERROR joining thread");
        exit(1);
    }
    if(count < 2 * NITER)
        printf("\n BOOM! count is [%d], should be %d\n", count, 2 * NITER);
    else
        printf("\n OK! count is [%d]\n", count);
    pthread_exit(NULL);
}

Upvotes: 0

Views: 649

Answers (1)

DrC
DrC

Reputation: 7698

The clang error is because ThreadAdd is declared as void * and doesn't return anything. Just return 0.

One issue is that sem_wait and sem_post can fail. In that case, they return -1 and you need to check errno for the cause. Your code looked okay to me so I tried it on two machines: - SE Linux, worked just fine - Mac, sem_wait failed.
So the direct problem is you aren't checking the return value.

I found another post that stated sem_init is NOT supported on OS X (yeah Apple) but that sem_open is supported. I tried your code using sem_open and it worked. Nothing in the docs that I could see gave any hint this was the case. I'd link to the other post but I lost the address in a machine change...

I see Jack also posted this...

Upvotes: 1

Related Questions