wait and notify in C/C++ shared memory

前端 未结 6 807
旧巷少年郎
旧巷少年郎 2020-12-13 04:21

How to wait and notify like in Java In C/C++ for shared memory between two or more thread?I use pthread library.

6条回答
  •  臣服心动
    2020-12-13 05:04

    If you do not care about portability, Linux offers eventfd, which gives you exactly what you want. Each eventfd keeps an internal counter. In the default mode, reading from the eventfd blocks if the counter is zero, otherwise returns immediately. Writing to it will add to the internal counter.

    The wait call would thus just be a uint64_t buf_a; read(event_fd, &buf_a, sizeof(buf_a));, where buf must be an 8-byte buffer. To notify the waiting thread, you would do uint64_t buf_b = 1; write(event_fd, &buf_b, sizeof(buf_b));.

提交回复
热议问题