簡體   English   中英

應用信號量后,代碼仍無法按預期工作

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

以下代碼應輸出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);
}

鐺錯誤是因為ThreadAdd被聲明為void *並且不返回任何內容。 只需返回0。

一個問題是sem_wait和sem_post可能失敗。 在這種情況下,它們將返回-1,並且您需要檢查errno以查找原因。 您的代碼對我來說還不錯,所以我在兩台計算機上進行了嘗試:-SE Linux,工作正常-Mac,sem_wait失敗。
因此,直接的問題是您沒有檢查返回值。

我發現另一篇文章指出OS X(是的,Apple)不支持sem_init,但支持sem_open。 我使用sem_open嘗試了您的代碼,它起作用了。 我所看到的文檔中沒有任何跡象表明情況確實如此。 我會鏈接到另一篇文章,但是我在換機時丟失了地址...

我看到傑克也發布了這個...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM