下面的代码应该输出 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);
}