Created
August 15, 2012 14:40
-
-
Save christianparpart/3360676 to your computer and use it in GitHub Desktop.
POSIX threads (pthread): multiple reader one writer demo
This file contains hidden or 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
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <pthread.h> | |
| #include <unistd.h> | |
| #include <list> | |
| bool quitting = false; | |
| int data = 0; | |
| pthread_rwlock_t rwlock = PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP; | |
| class Reader { | |
| int id_; | |
| pthread_t thread_; | |
| public: | |
| explicit Reader(int id) : | |
| id_(id) | |
| { | |
| pthread_create(&thread_, nullptr, &Reader::_run, this); | |
| } | |
| ~Reader() { | |
| pthread_join(thread_, nullptr); | |
| } | |
| void run() { | |
| while (!quitting) { | |
| pthread_rwlock_rdlock(&rwlock); | |
| printf("[%d]: %d\n", id_, data); | |
| pthread_rwlock_unlock(&rwlock); | |
| pthread_yield(); // junk | |
| } | |
| } | |
| private: | |
| static void* _run(void* p) { | |
| Reader* reader = static_cast<Reader*>(p); | |
| reader->run(); | |
| return nullptr; | |
| } | |
| }; | |
| void writer() { | |
| pthread_yield(); | |
| for (;;) { | |
| sleep(1); | |
| printf("rwlock: Acquiring for WRITE\n"); | |
| pthread_rwlock_wrlock(&rwlock); | |
| printf("rwlock: hardcore WRITE-action @.@ BEGIN\n"); | |
| data = data + 1; | |
| quitting = data == 42; | |
| sleep(2); | |
| printf("rwlock: hardcore WRITE-action @.@ DONE\n"); | |
| pthread_rwlock_unlock(&rwlock); | |
| } | |
| } | |
| int main(int argc, const char *argv[]) | |
| { | |
| srand(time(nullptr)); | |
| std::list<Reader*> readers; | |
| for (int i = 1, e = (argc == 2 ? atoi(argv[1]) : 4); i <= e; ++i) | |
| readers.push_back(new Reader(i)); | |
| writer(); | |
| for (auto reader: readers) | |
| delete reader; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment