Skip to content

Instantly share code, notes, and snippets.

@astarasikov
Created September 28, 2013 19:14
Show Gist options
  • Save astarasikov/6745437 to your computer and use it in GitHub Desktop.
Save astarasikov/6745437 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define LOOP_COUNT 30
#define NUM_THREADS 4
#define Q_SIZE 5
struct Fifo {
pthread_mutex_t mutex;
int data[Q_SIZE];
int head;
int count;
Fifo() : head(0), count(0) {
pthread_mutex_init(&mutex, 0);
}
void put(int value) {
while (1) {
pthread_mutex_lock(&mutex);
if (count < Q_SIZE) {
data[(count + head) % Q_SIZE] = value;
++count;
pthread_mutex_unlock(&mutex);
return;
}
pthread_mutex_unlock(&mutex);
}
}
int take(void) {
while (1) {
pthread_mutex_lock(&mutex);
if (count > 0) {
int ret = data[head % Q_SIZE];
++head;
--count;
pthread_mutex_unlock(&mutex);
return ret;
}
pthread_mutex_unlock(&mutex);
}
}
};
struct ThreadInfo {
Fifo *fifo;
int thread_num;
};
static void qlog(int thread_num, int val, bool is_put) {
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
std::cerr << " thread " << thread_num <<
(is_put ? " putting " : " took ") << val << std::endl;
pthread_mutex_unlock(&mutex);
}
static void *test_q(void *data) {
ThreadInfo *info = reinterpret_cast<ThreadInfo*>(data);
Fifo* fifo = info->fifo;
bool prod_cons = info->thread_num % 2;
int loop_count = 0;
while (++loop_count <= LOOP_COUNT) {
if (prod_cons) {
int val = rand();
qlog(info->thread_num, val, 1);
fifo->put(val);
}
else {
int val = fifo->take();
qlog(info->thread_num, val, 0);
}
}
return 0;
}
int main()
{
srand(time(0));
pthread_t threads[NUM_THREADS];
struct ThreadInfo infos[NUM_THREADS];
Fifo fifo;
for (int i = 0; i < NUM_THREADS; i++) {
infos[i].fifo = &fifo;
infos[i].thread_num = i;
pthread_create(threads + i, 0, test_q, infos + i);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], 0);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment