Skip to content

Instantly share code, notes, and snippets.

@xemoe
Last active December 2, 2016 16:12
Show Gist options
  • Save xemoe/b4061b52be7fab010ed15b8275800a7b to your computer and use it in GitHub Desktop.
Save xemoe/b4061b52be7fab010ed15b8275800a7b to your computer and use it in GitHub Desktop.
Parallel ball
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_CONCURRENT 10
pthread_mutex_t mutex;
pthread_cond_t condvar;
int race[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int winner[10];
int done = -1;
int parallel_round = 0;
int concurrent = 0;
void shuffle(int *array, size_t n)
{
if (n > 1)
{
struct timeval tv;
gettimeofday(&tv, NULL);
int usec = tv.tv_usec;
srand48(usec);
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = (unsigned int) (drand48()*(i+1));
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
void *task(int id) {
int wait = 1000000 * race[id];
usleep(wait);
if (done != 0) {
done = 0;
printf("Ball %d got %d\n", parallel_round + 1, id);
pthread_cond_signal(&condvar);
winner[parallel_round++] = id;
} else {
pthread_cond_signal(&condvar);
}
}
void *threaded_task(void *t) {
long id = (long) t;
concurrent++;
task(id);
concurrent--;
pthread_exit(0);
}
void *parallel(int num_tasks)
{
int num_threads = num_tasks;
pthread_t thread[num_threads];
int rc;
long t;
for (t = 0; t < num_threads; t++) {
rc = pthread_create(&thread[t], NULL, threaded_task, (void *)t);
if (rc) {
printf("ERROR: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condvar, NULL);
for (int i = 0; i < 7; i++) {
done = -1;
shuffle((int*) &race, 10);
parallel(10);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condvar, &mutex);
pthread_mutex_unlock(&mutex);
while (concurrent > MAX_CONCURRENT) {
printf("Wait for reach maxmimum concurrent\n");
usleep(300000);
}
}
printf("-------------------------\n");
printf("Main completed\n");
printf("-------------------------\n");
printf("-------------------------\n");
printf("Winner is %d %d %d %d %d %d %d\n", winner[0], winner[1], winner[2], winner[3], winner[4], winner[5], winner[6]);
printf("-------------------------\n");
pthread_exit(NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment