0
下面的代碼應該輸出NITER * 2,但它似乎仍然沒有互斥工作,任何想法?應用信號後,代碼仍然不能正常工作
爲什麼鐺給了我以下警告:
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);
}
-Wreturn型:你ThreadAdd函數返回「無效*」不「無效」。所以你需要返回NULL,如果你不需要返回一個值到主函數。 – goji
另外,如果你想要互斥功能,你爲什麼要使用信號量?改用pthread的互斥體。 – goji
此外,此代碼似乎輸出正確的值:OK!計數是[2000000] – goji