简体   繁体   English

使用eventfd进行同步时无法获取锁定

[英]Unable to get lock when eventfd is used for synchronization

I am trying to use eventfd for synchronization b/w two threads. 我正在尝试使用eventfd进行黑白同步两个线程。 Please look below code. 请看下面的代码。 In this if main thread acquires a lock first it wont release unless I uncomment sleep after write function. 在这种情况下,除非主线程首先获取了锁,否则除非我在写函数后取消注释睡眠,否则它将不会释放。 It is true if thread gets the lock first. 如果线程先获得锁,这是事实。 Please let me know how to handle without using sleep after write. 写完后,请让我知道如何不使用睡眠。

#include <pthread.h>
#include <stdint.h> 
#include <stdio.h>
int event_fd;
uint64_t counter;
void * Thread1(void *p)
{
    printf("\n%s eventfd = %d\n",(char*)p, event_fd);

    while(1)
    {
        read(event_fd, &counter,sizeof(counter));
        printf("\n %s function counter = %llu\n",(char*)p,counter);
        sleep(1);
        write(event_fd,&counter,sizeof(counter));
        //sleep(1);     
     }

    return NULL;
}

void main()
{
    char str[]="In Thread1";
    int ret;

    pthread_t p_th;
    printf("Events demonstration pid = %d sizeof counter %lu\n ",getpid(),sizeof(counter));
    event_fd=eventfd(1,0);
    printf("event_fd %d\n",event_fd);
    pthread_create(&p_th,NULL,Thread1, str);    
    while(1)
    {
        read(event_fd, &counter,sizeof(counter));
        printf("\n In main function counter = %llu\n",counter);
        sleep(1);
        write(event_fd,&counter,sizeof(counter));   
        //sleep(1); 
    }

    pthread_exit (NULL);
}

Firstly, they aren't locks. 首先,它们不是锁。 They are eventfd semaphores. 它们是eventfd信号量。

Secondly, they contain no provision for fairness amongst threads. 其次,它们不包含线程间公平性的规定。 So if you omit the sleep() clause, the semaphore will be grabbed again the moment you release it by the next read . 因此,如果省略sleep()子句,则在下次read释放该信号量时,该信号量将再次被抓住。 eventfd is more often used in a producer consumer environment where one end is doing the write and the other the read . eventfd更常用于生产者消费者环境,其中一端进行write ,另一端进行read

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM