Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <stdint.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <sys/eventfd.h>
- #define SIZE 20
- pthread_t threads[SIZE];
- int fd; /* event file descriptor */
- int counter = 0;
- void lock(int fd)
- {
- int64_t value;
- int ret = read(fd, &value, sizeof(int64_t));
- if(ret == -1) printf("ERROR: read\n");
- }
- void unlock(int fd)
- {
- int64_t value = 1;
- int ret = write(fd, &value, sizeof(int64_t));
- if(ret == -1) printf("ERROR: write\n");
- }
- void* execute(void* arg)
- {
- for(int i = 0; i < 1000; i++)
- {
- lock(fd);
- counter += 1;
- unlock(fd);
- }
- }
- void init_threads()
- {
- for(int i = 0; i < SIZE; i++)
- pthread_create(&threads[i], NULL, execute, NULL);
- }
- void destroy_threads()
- {
- for(int i = 0; i < SIZE; i++)
- pthread_join(threads[i], NULL);
- }
- int main(void)
- {
- /* create event file descriptor with initval=1 and options=0 */
- fd = eventfd(1, 0);
- init_threads();
- destroy_threads();
- printf("Counter: %d\n", counter);
- return 0;
- }
Add Comment
Please, Sign In to add comment