我正在尝试计算在某个其他线程释放信号量时获取信号量所需的时间。所以我的愿景是创建2个线程并将信号量从一个线程释放到另一个线程,并计算释放和获取之间的时间。
现在是我的代码:
void* semaphore_keeper(void* w_args)
{
struct sema_mutex_args_struct* args = (struct sema_mutex_args_struct*)w_args;
sem_t* id = args->id;
int* status = args->status;
pthread_barrier_t* barr = args->barr;
while(*status != -1)
{
printf("keeper waits sema\n");
sem_wait(id);
printf("keeper got sema waiting for barr\n");
pthread_barrier_wait(barr);
printf("keeper waited barr\n");
clock_gettime(CLOCK_REALTIME, start);
printf("keeper sent clock\n");
sem_post(id);
printf("keeper posted sema\n");
}
return NULL;
}
void semaphore_mutex_not_empty(int w_iterations, int w_drop_cache)
{
start = mmap(NULL, sizeof(struct timespec), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
finish = mmap(NULL, sizeof(struct timespec), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
sem_t* id;
int* status = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
*status = 4;
if((id = sem_open("threadsem", O_CREAT, 0600, 0)) == SEM_FAILED)
{
perror("sem_open");
}
sem_post(id);
struct sema_mutex_args_struct args;
args.id = id;
args.status = status;
args.barr = malloc(sizeof(pthread_barrier_t));
pthread_barrier_init(args.barr, NULL, 2);
pthread_t thread_creation;
pthread_create(&thread_creation, NULL, semaphore_keeper, (void*)&args);
double totSemaphore = 0.0;
for(int i = 0; i < w_iterations; i++)
{
printf("mama waits on barr\n");
pthread_barrier_wait(args.barr);
printf("mama got past barr, waiting for sema now\n");
sem_wait(id);
printf("got sem\n");
clock_gettime(CLOCK_REALTIME, finish);
double thisTime = (finish->tv_nsec - start->tv_nsec);
totSemaphore += (finish->tv_nsec - start->tv_nsec);
printf("%f\n", thisTime);
printf("mama posting sema\n");
sem_post(id);
}
// very ugly
*status = -1;
pthread_join(thread_creation, NULL);
....
我认为这段代码应该有效,因此障碍使线程彼此等待,因此它不会被摧毁。但是,当我运行程序时,我得到的输出如下所示(第一次迭代):
mama waits on barr
keeper waits sema
keeper got sema waiting for barr
keeper waited barr
mama got past barr, waiting for sema now
got sem
keeper sent clock
keeper posted sema
keeper waits sema
keeper got sema waiting for barr
-1567.000000
所以线程就像它们应该在屏障上相互等待,但似乎主线程甚至在子线程释放之前就获得了信号量。这是为什么?我究竟做错了什么?如上所述,参考输出仅来自第一次迭代。它似乎在第一次迭代后得到修复(至少给出正值),但我不相信它们也是正确的值,因为它在第一次迭代中也已经搞砸了。