0

下面的代码应该输出 NITER * 2,但似乎仍然没有互斥锁工作,知道吗?

以及为什么clang给我以下警告:

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

代码:

#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);
}
4

1 回答 1

1

clang 错误是因为 ThreadAdd 被声明为 void * 并且不返回任何内容。只需返回 0。

一个问题是 sem_wait 和 sem_post 可能会失败。在这种情况下,它们返回 -1,您需要检查 errno 的原因。您的代码对我来说看起来不错,所以我在两台机器上进行了尝试: - SE Linux,工作正常 - Mac,sem_wait 失败。
所以直接的问题是你没有检查返回值。

我发现另一篇文章指出 OS X(是的 Apple)不支持 sem_init,但支持 sem_open。我使用 sem_open 尝试了您的代码并且它有效。我能看到的文档中没有任何暗示是这种情况。我会链接到另一篇文章,但我在机器更改中丢失了地址......

我看到杰克也发布了这个......

于 2012-10-28T04:11:24.177 回答