This repository has been archived by the owner on Nov 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 390
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
74 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
#include <stdio.h> | ||
#include <uv.h> | ||
|
||
uv_barrier_t blocker; | ||
uv_rwlock_t numlock; | ||
int shared_num; | ||
|
||
void reader(void *n) | ||
{ | ||
int num = *(int *)n; | ||
int i; | ||
for (i = 0; i < 20; i++) { | ||
uv_rwlock_rdlock(&numlock); | ||
printf("Reader %d: acquired lock\n", num); | ||
printf("Reader %d: shared num = %d\n", num, shared_num); | ||
uv_rwlock_rdunlock(&numlock); | ||
printf("Reader %d: released lock\n", num); | ||
} | ||
uv_barrier_wait(&blocker); | ||
} | ||
|
||
void writer(void *n) | ||
{ | ||
int num = *(int *)n; | ||
int i; | ||
for (i = 0; i < 20; i++) { | ||
uv_rwlock_wrlock(&numlock); | ||
printf("Writer %d: acquired lock\n", num); | ||
shared_num++; | ||
printf("Writer %d: incremented shared num = %d\n", num, shared_num); | ||
uv_rwlock_wrunlock(&numlock); | ||
printf("Writer %d: released lock\n", num); | ||
} | ||
uv_barrier_wait(&blocker); | ||
} | ||
|
||
int main() | ||
{ | ||
uv_barrier_init(&blocker, 4); | ||
|
||
shared_num = 0; | ||
uv_rwlock_init(&numlock); | ||
|
||
uv_thread_t threads[3]; | ||
|
||
int thread_nums[] = {1, 2, 1}; | ||
uv_thread_create(&threads[0], reader, &thread_nums[0]); | ||
uv_thread_create(&threads[1], reader, &thread_nums[1]); | ||
|
||
uv_thread_create(&threads[2], writer, &thread_nums[2]); | ||
|
||
uv_barrier_wait(&blocker); | ||
uv_barrier_destroy(&blocker); | ||
|
||
uv_rwlock_destroy(&numlock); | ||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters