#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>
int evfd;
void * f(void *p)
{
int ret = 0,j = 100;
while(ret >= 0)
{
uint64_t i = 0;
fd_set readfds,allfds;
FD_SET(evfd,&readfds);
FD_SET(evfd,&allfds);
int fds = select(evfd + 1,&readfds,0,0,0);
if(FD_ISSET(evfd,&allfds))
{
ret = read(evfd,&i,sizeof(int64_t));
printf("%d,%d,%llu\n",pthread_self(),ret,i);
}
}
printf("pid=%d exit\n",pthread_self());
}
int main(int argc, char *argv[])
{
//evfd = eventfd(1000,EFD_NONBLOCK|EFD_CLOEXEC);
evfd = eventfd(1000,0);
pthread_t pid1 = 0,pid2 = 0,pid3 = 0;
pthread_create(&pid1,0,f,0);
//pthread_create(&pid2,0,f,0);
//pthread_create(&pid3,0,f,0);
printf("pid=%d,%d,%d\n",pid1,pid2,pid3);
sleep(1);
uint64_t j = 100;
int ret = write(evfd,&j,sizeof(uint64_t));
printf("write j=%d,%d\n",j,ret);
sleep(1);
j++;
ret = write(evfd,&j,sizeof(uint64_t));
printf("write j=%d,%d\n",j,ret);
//這句注釋,得出的結論差異很大.
//應該多次(連續兩次)寫,讀方一次讀,8 位元組的核心計數緩衝區寫亂了
//所以,證明write 能觸發讀操作,但是具體觸發幾次讀操作,還需要讀
//操作自己控制,否則寫次數 != 讀次數,理論上要完全符合也很難
//操作上應該是觸發讀後,讀操作後的動作需要合理的判斷結束點
//sleep(1);
j++;j++;
ret = write(evfd,&j,sizeof(uint64_t));
printf("write j=%d,%d\n",j,ret);
sleep(1);
j++;j++;
ret = write(evfd,&j,sizeof(uint64_t));
printf("write j=%d,%d\n",j,ret);
sleep(1);
close(evfd);
return 0;
}
輸出:
gcc cc.c -o cc -lpthread;./cc
pid=-1553656064,0,0
-1553656064,8,1000
write j=100,8
-1553656064,8,100
write j=101,8
write j=103,8
-1553656064,8,204
write j=105,8
-1553656064,8,105
這裡,連續寫了兩次,讀了一次,導致緩衝區亂了。
write j=101,8
write j=103,8
-1553656064,8,204