Skip to content

Instantly share code, notes, and snippets.

@realModusOperandi
Last active November 9, 2022 07:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realModusOperandi/5624767 to your computer and use it in GitHub Desktop.
Save realModusOperandi/5624767 to your computer and use it in GitHub Desktop.
May I present.... PARALLEL FIZZBUZZ (with no safeties).
//
// main.c
// 2fast2fizzbuzz
//
#include <stdio.h>
#include <pthread.h>
#include <sched.h>
typedef struct {
int number;
int *go;
} thread_info;
void* do_thread(void *arg) {
char text[33];
thread_info ti = *(thread_info*)arg;
int i = ti.number;
int *go = ti.go;
while (!*go) { }
if (i % 15 == 0) {
sprintf(text, "FizzBuzz");
}
else if (i % 3 == 0) {
sprintf(text, "Fizz");
}
else if (i % 5 == 0) {
sprintf(text, "Buzz");
}
else {
sprintf(text, "%d", i);
}
char *ptr = text;
while (*ptr) {
putchar(*ptr++);
pthread_yield_np();
}
putchar('\n');
return NULL;
}
int main(int argc, const char * argv[])
{
int num_threads = 100;
pthread_t threads[num_threads];
thread_info threads_info[num_threads];
int go = 0;
for (int i = 0; i < num_threads; i++) {
threads_info[i].number = i+1;
threads_info[i].go = &go;
pthread_create(&threads[i], NULL, do_thread, (void*)&threads_info[i]);
}
go = 1;
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
12F14BBFF2728FFBB21FF2121FF3131FF3BB4FF3434F44F4BF55FB5F55F66F6BF66FB7F77F77F7BF88FB8F88FF9
9F9BF99FB
i9
uuiui23iu6i89i12i4ui78iu1i34i67i9ui23iu6i8912i4uii8iu
zzzzz
zz
z
z
z
zz
zz
z
z
z
zz
2
zz
z
z
zzzz
zzzzzzzzzzz3zzzzzzzzzz
zzzzzzzzzz
i
B
i
B
u
u
6
zuzuzz
zzzzzz
1z
z
ii8394ii1627ii4uu1ii7384i67i9ii7zz
zz
zz
z
z
zz
zzzzzzzzzz
BBuuzzzz
zzzz
zzBuzz
zzBuzz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment